AngularJS : scope
To make the link between model, view and controller AngularJS provides the scope. The scope is an object which can be transported between the model, the view and the controller. Each component will manage its own scope inheriting the scope of the parent or the root scope ($rootScope). Each scope can see the properties of the parent.
The link is the view through the DOM tree, a scope is always attached to a node in the DOM tree. The root scope is attached to the node containing ng-app directive, via an attribute and initialize the AngularJS application. Most of the time the ng-app attribute is declared in the html tag but it can be declared anywhere. To facilitate debugging it is possible to access the scope via the DOM tree by calling angular.element(aDOMElement).scope().
The scope can also interact with the data-binding: method $watch(property, function) intercepts changes on the model property “property” and triggers the “function“. Function $apply() dispatch modification on the view.
Some directives create a child scope such as ng-controller or ng-repeat. It is not a requirement in the directives creation. The idea is to isolate component behavior in some cases.
A good example of showing how the scope work is the one on the AngularJS documentation listed below. It uses the feature event of the scope. It allows you to send an event to parent scopes $emit, or to child scopes : $broadcast by calling $on function. The example outputs a triggering event counter, the counter depends on the scope targeted.
The concept of scope is important to introduce the directives in the next post.