Scope In AngularJS

Introduction

$scope in AngularJS is object which refers as an application model. It is object that bind view (DOM element) with the controller. In controller, model data is accessed via $scope object. As we know, AngularJS supports MV* pattern, $scope object becomes the model of MV*.

The $scope is a special JavaScript object. Both View and controller have access to the scope object. It can be used to communication between view and controller. Scope object contains both data and functions. Every AngularJS application have a $rootScope that is the top most scope created on DOM element which contains the ng-app directive. It can watch expressions and propagate events.

Characteristics of scope object

  • It provide the APIs to observe model (example $watch).
  • It can be nested, so that it limits access to the properties. Nested scopes are either child scope or isolated scope.
  • It provide the APIs to propagate any model changes from the outside of "Angular realm" (example $apply).
  • It provide context against expression to be evaluated.

Scope Inheritance

Scope is controller specific. Every Angular application has only one root scope but may have many child scopes. Some directives create new scope, so that the application may have multiple scopes. Whenever any new scope is created, they are added as child of parent scope. It creates a tree structure.

When Angular evaluates any expression, it first looks at the scope that is associated with current element. If no such property is found it looks into parent scope. This process is recursive until the root scope. This is known as "prototypical inheritance" in JavaScript.

root scope

Example

In the following example, I have created three controllers: parentController, firstChildControllerand secondChildController and defined one property in each controller parentName, level1name and level2name respectively. Here controllers are attached with DOM element in a nested way.

As described above, AngularJS evaluates expression with current associated scope and then it search in parent scope and so on until the root scope is reached.

TestAngularJs.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>AngularJS Test Application</title>  
  5.     <script src="angular.js"></script>  
  6. </head>  
  7. <body ng-app="myapp">  
  8.     <h2>AngularJS - Scope Inheritance</h2>  
  9.     <div ng-controller="ParentController">  
  10.         <div ng-controller="firstChildController">  
  11.             <div ng-controller="secondChildController">  
  12.                 <p>Parent Name:{{parentName}}</p>  
  13.                 <p>First Child Name:{{level1name}}</p>  
  14.                 <p>Second Child Name:{{level2name}}</p>  
  15.             </div>  
  16.         </div>  
  17.     </div>  
  18.   
  19.     <script>  
  20.         var app = angular.module("myapp", []);  
  21.   
  22.         app.controller("ParentController", function ($scope) {  
  23.             $scope.parentName = "Parent Controller";  
  24.         });  
  25.   
  26.         app.controller("firstChildController", function ($scope) {  
  27.             $scope.level1name = "First Child Controller";  
  28.         });  
  29.         app.controller("secondChildController", function ($scope) {  
  30.             $scope.level2name = "Second Child Controller";  
  31.         });  
  32.   
  33.     </script>  
  34. </body>  
  35.   
  36. </html>  
Output

run

Scope Events Propagation

Events can be propagating to the DOM in similar fashion. The events can be emitted or broadcast to scope parents and child respectively.

Example


AngularJS app
  1. var app = angular.module("myapp", []);  
  2.   
  3. app.controller('EventPropagationController', ['$scope', function ($scope) {  
  4.     $scope.count = 0;  
  5.     $scope.$on('MyEvent', function () {  
  6.         $scope.count++;  
  7.     });  
  8. }]);  
HTML

 

  1. <h2>AngularJS - Scope Events Propagation</h2>  
  2. <div ng-controller="EventPropagationController">  
  3.     Root scope "MyEvent"" count: {{count}}  
  4.     <div ng-controller="EventPropagationController">  
  5.         <button ng-click="$emit('MyEvent')">Emit - 'MyEvent'</button>  
  6.         <button ng-click="$broadcast('MyEvent')">Broadcast('MyEvent')</button>  
  7.         <br>  
  8.         First level - scope "MyEvent" count: {{count}}  
  9.         <div  ng-controller="EventPropagationController">  
  10.             Last level - scope "MyEvent" count: {{count}}  
  11.         </div>  
  12.     </div>  
  13. </div>  
Output

Output

Scope Life Cycle

In any JavaScript flow, when browser received an event it executes a corresponding JavaScript callback and browser re-render the DOM object when the callback completes. When browser executes any JavaScript code outside the Angular Context, The AngularJS is unaware about model changes. Using $apply method, model changes can be detected in Angular Context. The $apply method calls $digest after evaluating the expression for examining all of the $watch expressions and compares them with the previous value. There is some specific cycle of scope.
  1. Creation: Using $injector, the root scope is created during application bootstrap. Some of the directive creates new child scope during the template linking.

  2. Watcher registration: The $watch is required to propagate model values to the DOM. Directives register watch on the scope during the template linking.

  3. Model mutation: Using API $apply, mutation to be properly observed.

  4. Mutation observation: At the end of $apply, AngularJS perform $digest on the root scope. It updates all model properties value propagation.

  5. Scope destruction: When child scope is no longer required, child scope is automatically destroyed. This is the responsibility of the child scope creator to destroy them using $scope.$destroy() API. It will stop model propagation and release memory.

    Scope destruction

Summary

Scope is an important feature of AngularJS. Using this article, we can learn AngularJS scoped.

Hope this will help you.


Similar Articles