Why ng-app can be put in any tag?

227 Views Asked by At

I am new to AngularJS. I'd like to know what is the difference if I place ng-app in either <html> tag or <body> or <div>. Similarly same doubt for ng-controller .

2

There are 2 best solutions below

0
On

Where ever you put ng-app the elements inside it can only access the module and ng-controller can be used only when you have used ng-app in some upper element...

The controllers are accessible only if the module is initialised which is done using ng-app statement..

remember that the mmodule needs to be initialised only once and on an element under which you want all the angular controllers functionality for your various elements

0
On

The positioning of tag ng-controller defines the visibility and usage of scope

<div ng-controller="outerController" id="outerController">
    //outerController $scope is available here
    //innerController $scope is **not** available here

    <div ng-controller="innerController" id="innerController">
        //outerController $scope is available here
        //myControllers $scope is available here
    </div>
</div>

Nested controllers will search for elements on the closest bound scope first before ascending the chain.

For example imagine $scope.outerVar is set on the outerController

If innerController attempts to access $scope.outerVar then a check is done to see if this property is set on the innerController first. Only if it is not set will it go up the chain to outerController to retrieve it from there.