Mastering Web Application

(Rick Simeone) #1
Chapter 1

AngularJS is not intrusive and lets us keep model objects free from
any framework-specific code.

Scopes in depth

Each $scope is an instance of the Scope class. The Scope class has methods that
control the scope's lifecycle, provide event-propagation facility, and support the
template rendering process.


Hierarchy of scopes


Let's have another look at the simple HelloCtrl example, which we've
examined already:


var HelloCtrl = function ($scope) {
$scope.name = 'World';
}

The HelloCtrl looks similar to a regular JavaScript constructor function, there is
absolutely nothing special about it apart from the $scope argument. Where might
this argument might be coming from?


A new scope was created by the ng-controller directive using the Scope.$new()
method call. Wait a moment; it looks like we need to have at least one instance of a
scope to create a new scope! Indeed, AngularJS has a notation of the $rootScope
(a scope that is a parent of all the other scopes). The $rootScope instance gets
created when a new application is bootstrapped.


The ng-controller directive is an example of a scope-creating directive. AngularJS
will create a new instance of the Scope class whenever it encounters a scope-creating
directive in the DOM tree. A newly-created scope will point to its parent scope using
the $parent property. There can be many scope-creating directives in the DOM tree
and as a result many scopes will be created.


Scopes form a parent-child, tree-like relationship rooted at the
$rootScope instance. As scopes' creation is driven by the DOM tree,
it is not surprising that scopes' tree will mimic the DOM structure.

Now that we know that some directives create new child scopes you might be
wondering why all this complexity is needed. To understand this, let's have a look
at the example that makes use of a ng-repeat repeater directive.

Free download pdf