How to use ng-app and ng-controller in AngularJS

Before you start this tutorial, make sure you’ve already downloaded the AngularJs file in your file directory. Go here to download.

Explanation

  • Notice that in line 1 of the html section, we’ve included our application, and in line 5, we’ve included our controller.

  • In lines 24 to 32, we set up an IIFE (Immediately Invoked Function Expression). This enables our script to work immediately after the page loads.

Note: IIFE is a function associated with AngularJS.

  • In line 25, we include the use strict in our code. This is to check for any errors in the code as we work.

  • In line 26, we set up our application by typing angular.module, and follow it with a round bracket. This includes the name of our application, followed by a comma and empty square brackets.

Note: No comma is put after the closing of the round brackets.

  • In line 27, we set up a controller with .controller, the name of our controller, and the name of the function that will perform all the work.

  • In line 29, we set up the function.

We can use the ng-app by including it in the start tag html element, or the body element in our index.html in this syntax:

// ng-app="nameOfApp"

While ng-controller can be used by including it in the start tag of the element, we want it to have an effect on this syntax:

// ng-controller="nameOfCtrl"

Note: The controller will have an effect on any element below the element it was specified on.

Note: The script will be in a separate js file and not in our downloaded AngularJS file. Both are included in our index.html so that it will work.

Free Resources