Reputation: 817
I was going through the ng-controller tutorial on angularjs.org website. I came across a scope inheritance example in http://jsfiddle.net/api/post/library/pure/ . Here the author says the ng-controller directive creates a new child scope, i.e in the scope inheritance example we have 3 controllers and 4 scopes. Hows does this happen?. the code from the fiddle is below:
Javascript:
var myApp = angular.module('scopeInheritance', []);
myApp.controller('MainCtrl', ['$scope', function($scope){
$scope.timeOfDay = 'morning';
$scope.name = 'Nikki';
}]);
myApp.controller('ChildCtrl', ['$scope', function($scope){
$scope.name = 'Mattie';
}]);
myApp.controller('GrandChildCtrl', ['$scope', function($scope){
$scope.name = 'Gingerbreak Baby';
}]);
There is some problem with the fiddle link, so attaching rest of the code below:
HTML:
<div ng-app="scopeInheritance">
<div ng-app="scopeInheritance" class="spicy">
<div ng-controller="MainCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
<div ng-controller="ChildCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
<div ng-controller="GrandChildCtrl">
<p>Good {{timeOfDay}}, {{name}}!</p>
</div>
</div>
</div>
</div>
</div>
Upvotes: 2
Views: 1011
Reputation: 67306
Without seeing the exact markup, it is difficult to tell, however, if each of these controllers is used once, then you would have 3 scopes + root scope.
When Angular encounters directives (built in or otherwise) that define themselves as needing a scope, then a new scope is created. This is done in the scope
property of the directive and you can find documentation about that in the directive docs.
ng-controller
is a built-in Angular directive that requires a new inherited scope. So, when Angular is compiling the DOM tree, it will create scopes for each controller. So, that accounts for 3 of the 4 scopes.
There is also a special scope that ng-app
directive defines called $rootScope
. The $rootScope
is the top-level parent scope on the page. So, this accounts for the fourth scope.
Hope this helps.
Upvotes: 1