What is scope in AngularJS?
Scope is a
special JavaScript object that refers to the application model, you can
consider this as a view model.
Scope objects Basic
Scope
objects contain functionality and data that is used when rendering the view,
reason Scopes are the source of truth for the application state.
Because of
scope objects two-way automatic binding is possible in AngulaJS.
Scope features
1) Scopes
provide APIs ($watch) to observe model changes.
2) Scopes
provide APIs ($apply) to propagate model changes through the application as
well as outside the system to other components associated (controllers,
services, Angular event handlers).
3) Scopes
can be nested in such a way that they can isolate functionality and model
properties.
4) Scopes provide context against which
expressions are evaluated.
For example expression
{{FirstName}} is meaningless without
scope which defines property “FirstName”.
Scope as Data-Model
Scope is the
main communication gateway between application controller and the view.
During
Template linking phase directive apply $watch expressions on scope then which
allows the directive to render the updated value to the DOM.
<body>
<div ng-app="myApp" ng-controller="MyController">
Your name:
<input type="text"
ng-model="username">
<button ng-click='DsiplayMessage()'>Show Message</button>
<hr>
{{WelcomeMessage}}
</div>
<script>
angular.module('myApp',
[])
.controller('MyController',
['$scope', function ($scope) {
$scope.username = 'Shourya Kendre';
$scope.DisplayMessage
= function () {
$scope.WelcomeMessage = 'Welcome Mr. , ' +
$scope.username + '!' + 'From , Team
CodeChef4u';
};
}]);
</script>
</body>
In the above
example MyController assigns “Shourya Kendre” to the username property of the
scope. The scope then notifies the input of the assignment, which then renders
the input with username pre-filled. This demonstrates how a controller can
write data into the scope.
Similarly
the controller can assign behavior to scope as seen by the DisplayMessage method, which is invoked when the
user clicks on the button. The DisplayMessage method
can read the username property and create a greeting property. This
demonstrates that the properties on scope update automatically when they are
bound to HTML input widgets
Scope Hierarchies:
Your angular
app allows exactly only one root scope but you can add more child scopes in
your application.
When new
scopes are created they are added as children of their parent scope. This
creates a tree structure which parallels the DOM where they're attached.
Example:
Root scope
is available for entire application, in following example surname “Kendre” is
in root scope and names are in child scope.
<div ng-app="myApp" >
<!--root scope-->
Surname: {{scopeName}}
<div ng-controller="myCtrl">
<ul>
<!--child scopes-->
Names <li ng-repeat="name in names">{{name}}</li>
</ul>
</div>
</div>
<script>
var app =
angular.module('myApp', []);
app.run(function
($rootScope) {
$rootScope.scopeName =
'Kendre';
});
app.controller('myCtrl',
function ($scope) {
$scope.names = ["Nagnath", "Aditya", "Ajay"];
});
</script>
Scope lifecycle:
Here I will
try to explain sequence of actions performed with angularJS Scopes when we execute
application.
1. Creation
When AngularApp
page starts exaction during bootstrap process root scope is created by the
$injector.
During
template linking, some directives create new child scopes.
2. Watcher registration
During
template linking, directives register watches on the scope. These watches will
be used to propagate model values to the DOM.
3. Model mutation
For
mutations to be properly observed, you should make them only within the
scope.$apply(). Angular APIs do this implicitly, so no extra $apply call is
needed when doing synchronous work in controllers, or asynchronous work with
$http, $timeout or $interval services.
4. Mutation observation
At the end
of $apply, Angular performs a $digest cycle on the root scope, which then
propagates throughout all child scopes. During the $digest cycle, all $watched
expressions or functions are checked for model mutation and if a mutation is
detected, the $watch listener is called.
5. Scope destruction
This is concept
like memory releasing or cleaning unused objects in classic C++ or C
programming.
When child scopes
are not required its responsibility of creater to destroy child scopes using
scope.$destroy()
API.This will stop propagation of $digest calls into the child scope and allow
for memory used by the child scope models to be reclaimed by the garbage
collector.
Reference used:
Used angularjs.org
developer guide docs.
Special
thanks to aangularjs.org documentation team.