AngularJS Scope Life Cycle – Characteristics, Inheritance, $Scope Object

As we know that AngularJS directives can interact with the controller of a page but how it is possible? What made it possible to pass an object through directive? Well, directives have a scope associated with it which made all these things possible in angular. Let us explore the new topic, AngularJS Scope.

In this AngularJS Scope tutorial, we will learn why scope is used in AngularJS with its lifecycle and characteristics. Along with this, we will learn $rootscope, methods of $scope object, Scope as data model and inheritance.

So, let’s start the AngularJS Scope.

AngularJS Scope Tutorial

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

What is AngularJS Scope?

An AngularJS Scope is a built-in object. It is available for both view (HTML part) and controller. For every controller, angular creates or injects $scope object in angular. Therefore, the behavior attached in one controller cannot be accessed by another controller in AngularJS.

During the constructor definition, the first argument passed through controller is the $scope.

Syntax-

<script>
var mainApp = angular.module("mainApp", []);
 mainApp.controller("shapeController", function($scope) {
  $scope.message = function(Fname,Lname)
   {
  return Fname + Lname;
   }
 });
</script>

Why AngularJS Scope is used?

To define member variables, AngularJS scope is used within a controller. It can contain variables that are the application data and methods.

Syntax-

<script>
var mainApp = angular.module("mainApp", []);
 mainApp.controller("shapeController", function($scope) {
 $scope.message = "Property is defined here";
 });
</script>

In the above code “message ” is the member variable and its value is defined using $scope object. So wherever we display a message in view part its value will now get displayed as “property is defined here”.

  • It is used to transfer data from view to controller as well as to transfer data from a controller to view.
  • It acts as a linking between view and controller.
  • Functions can be defined using a $scope.

Do you know How to implement View in AngularJS?

<script>
var mainApp = angular.module("mainApp", []);
 mainApp.controller("shapeController", function($scope) {
  $scope.message = function(Fname,Lname)
   {
  return Fname + Lname;
    }
 });
</script>

$rootscope

An angular application contains a single $rootscope. All other $scope present in an angular application are the child objects. The $rootscope object is the parent of all other $scope object.

The behavior attached to $rootscope is available to all the controllers present in that particular angular application. It means the properties and methods attached to it can be accessed by all controllers.

NOTE- The difference between $scope object and $rootscope object is that behavior attached with $rootscope is available for all the controllers while behavior attached with $scope is attached with a specific controller in which it is defined.

<!DOCTYPE html>
<html>
<head>
   <title>AngualrJS Controller</title>
   <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
   <div ng-controller="parentController">
     Controller Name: {{controllerName}} <br />
     Message: {{msg}} <br />
     <div style="margin:10px 0 10px 20px;" ng-                      controller="childController">
        Controller Name: {{controllerName}} <br />
        Message: {{msg}} <br />
       </div>
     </div>  
   <div ng-controller="siblingController">
     Controller Name: {{controllerName}} <br />
     Message: {{msg}} <br />
   </div>
 <script>
     var ngApp = angular.module('myNgApp', []);

     ngApp.controller('parentController', function ($scope, $rootScope) {
        $scope.controllerName = "parentController";
        $rootScope.msg = "Common property of all controller ";
    });
      ngApp.controller('childController', function ($scope) {
        $scope.controllerName = "childController";
    });
      ngApp.controller('siblingController', function ($scope) {
         $scope.controllerName = "siblingController";
    });
  </script>
</body>
</html>

Output-

Controller Name: parentController
Message: This property is same for all controller.
Controller Name: childController
Message: This property is same for all controller.
Controller Name: siblingController
Message: Common property of all controller.

Explore the Dependency Injection in AngularJS

Explanation-

In the above code the property message is defined in parent controller only but since it is attached with $rootscope object, therefore, it remains the same for all the controller.

For Example-

In a piece of university information, the name of the student is a property that is distinct for every student so its behavior is attached with $scope object while the university name remains common for all the students so its behavior can be attached with a $rootscope object.

Various Methods of $Scope Object

  1. $eval() – The current scope expression is executed and the result is displayed.
  2. $apply() – Using this method an expression can be executed in angular outside the angular framework.
  3. $new() – A new child can be created using a $new method of $scope object.
  4. $on() – A callback for an event is registered using $on a method of $scope object.
  5. $destroy() – From parent scope, a current scope can be removed using $destroy method. As well as all its child scope is also removed using from parent scope.
  6. $emit() – A particular event is dispatched upwards till $rootscope using $emit method.
  7. $broadcast() – A particular event is dispatched downwards till $rootscope using a $broadcast method.

Life Cycle of AngularJS Scope

In the flow of javascript code, whenever an event is received by browser then it executes a javascript callback corresponding to it. And after the completion of callback, DOM objects are re-rendered by a browser. If any javascript code is executed outside the context of angularJS by browser then angularJS remain unaware with the changes in the model. To detect the model change in angularJS $apply API is used.

  1. Creation – During bootstrap of an application using $injector, root scope is created. And during the linking of a template, many of the directives creates new child scope.
  2. Watcher Registration – Model values can propagate to DOM using a $watch
  3. Model Mutation – To observe mutation in a proper way, an API known as $apply is used.
  4. Mutation Observation – After $apply, a $digest is performed on the root scope in angular JS.
  5. Scope Destruction – If child scope is no longer in use, then it should be destroyed. Child scope creator is responsible to destroy the child scope if no longer in use. Using API $scope.$destroy() child scope creator can do so. Destroying an unused child scope will release memory that is being used by it and stop model propagation too.

Life cycle of Scope in AngularJS

You must read – AngularJS Global API with types and examples

AngularJS Scope Characteristics

The various characteristics of the AngularJS scope are as follows:

  • Context is provided by the scope for expression. For example – We are displaying {{name}} in view part so it will be displayed as it is to a user until a value is attached to it and this work is done by scope. Scope provides value to property by $scope.name = “daisy”.
  • To observe model like a $watch, APIs are provided by scope.
  • Any model changes that is outside of “angular realm” can be propagated through the API provided by $scope.

AngularJS Scope as Data Model

AngularJS Scope is a link between the controller and view part. It is because values are attached with attributes through a scope in the controller part and it gets displayed in view part.

angular.module('scopeApp', [])
.controller('ScopeController', ['$scope', function($scope) {
$scope.tutorialname = 'angularJs';}]);

$WATCH

A $watch is an expression that notifies about any change in the property. So that an updated value gets render to DOM.

Recommended Reading – DOM in AngularJS

Scope Hierarchies

Every angularJS application can have only one root scope as it is the parent scope. But it can have more than one child scope. New scopes can be created by directives which are added to parent scope as child scope.

This is how a hierarchical structure such as a tree of scope is created.

How to Retrieve AngularJS Scope from the Directives

As a $scope data property, scopes are attached with DOM elements. Location of ng-app directive defines the location where root scope is attached to DOM. Generally, we put ng-app in the root element but if we want to control a particular part of our application we can also provide ng-app directive for that particular part. But it is declared only once in an angular application.

How to identify scope in a debugger

  • Select the element of your choice then right click on it you will get an option of ‘inspect element’ select it. You can now see a browser debugger along with a highlighted element that is the element selected by you for inspection.
  • The currently selected element can be accessed as $0 variable in a console, it is allowed by the debugger.
  • You have to execute angular.element($0).scope() to retrieve the associated scope in a console.

To make the scope function available $compileProvider.debugInfoEnabled() should be set true. And it is already set as a true value by default.

Scope Event Propagation

Like the DOM elements, AngularJS events can be propagated by scope too. Events can either be broadcasted to the child scope or emitted to the parent scope

  • $EMIT

It is a function used to propagate events. $EMIT propagates its upper side of the hierarchy of scope. It means if the event is in child scope it will get propagates at upwards means in the parent scope.

  • $BROADCAST

It is a function used to propagate events. $BROADCAST propagates it down the side of the hierarchy of scope. It means if the event is in child scope it will get propagates at downwards means in the second child scope.

AngularJS Scope Inheritance

Scope is basically controller specific. Whenever we nest a controller, that means to declare a controller inside a controller then the child controller inherits the scope of the parent controller.

AngularJS Scope Tutorial

 

<!Doctype html>
<html>
   <head>
      <title>Angular JS Forms</title>
   </head>
   
   <body>
      <div ng-app = "studentApp" ng-controller = "studentOne">
         <p>{{name}} <br/> {{grade}} </p>
         
         <div ng-controller = "studentTwo">
            <p>{{name}} <br/> {{grade}} </p>
         </div>
         
         <div ng-controller = "studentThree">
            <p>{{name}} <br/> {{grade}} </p>
         </div>
                        
      </div>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      
      <script>
         var t = angular.module("studentApp", []);
         
         t.controller("studentOne", function($scope) {
            $scope.name = "John";
            $scope.grade = "A";
         });
         t.controller("studentTwo", function($scope) {
            $scope.name = "jay";
         });
         t.controller("studentThree", function($scope) {
            $scope.name = "diva";
            $scope.grade = "B";
         });
                        
      </script>
      
   </body>
</html>

Output:

John
A

jay
A

diva
B

Summary

Therefore we can conclude that $scope is a built-in object that is used to define (assign value) member variable. As well as it can also be used to change the value of the member variable. A number of $scope object can be used inside a controller and it remains distinct for every controller.

You may also like to know 10 Reasons to learn AngularJS.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.