blog-image4

Understanding AngularJS $rootScope and $scope

Scope is an object that refers to the application model. It acts as glue between controller and view. Scopes are hierarchical in nature and follow the DOM (Document Object Model) structure of your angular app.

AngularJS has two scope objects: $rootScope and $scope.

$scope

A $scope is a JavaScript object which is used for communication between controller and view. Basically, $scope binds a view (DOM element) to the view model and functions defined in a controller.

$rootScope

The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.

AngularJS: $rootScope and $scope with example

external.js

       //defining module
var app = angular.module('IG', []);

//the run function acts as a main method for the angular app.
app.run(function ($rootScope) {
    $rootScope.site = "interviewgully.com";
    $rootScope.name = "Brajesh Kumar"
});

app.controller("myController", function ($scope, $rootScope) {
    $scope.name = "Sujeet Srivastava";
    $scope.welcome = "Welcome to " + $rootScope.site;
});

app.controller("testController", function ($scope, $rootScope) {
    $scope.welcome = "Welcome to " + $rootScope.site;
});




index.html

     <!DOCTYPE html>
<html  ng-app="IG">

<head>
    <title>AngularJS rootScope and scope :: InterviewGully.com</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
    <script src="Scripts/external.js"></script>
</head>

<body>
<div ng-controller="myController">
    <h1>rootScopeController</h1>
    <p>rootScope: {{site}}</p>
    
    <p>rootScope(ng-model): <input type="text" ng-model="site" /></p>

    <p>welcome from scope: {{welcome}}</p>
    <p>welcome from scope(ng-model): <input type="text" ng-model="welcome" /></p>
    <p>scope: {{name}}</p>
</div>

<div ng-controller="testController">
    <h1>ScopeController</h1>
    <p>rootScope: {{site}}</p>
    
    <p>rootScope(ng-model): <input type="text" ng-model="site" /></p>

    <p>welcome from scope: {{welcome}}</p>
    <p>name from rootScope: {{name}}</p>
</div>

<div>
<h1>Outside from both Controller</h1>
<p>name from rootScope: {{name}}</p>
<p>site from rootScope: {{site}}</p>
</div>
</body>
</html>




How it works

1. When you use ng-model with $rootScope objects then AngularJS updates those objects under a specific $scope of a controller but not at global level $rootScope.
blog-img

2. Create a private $scope for each controller to bind it to the view.

blog-img1

Understanding AngularJS scope life-cycle

Scope data goes through a life cycle when the angular app is loaded into the browser. Understanding the scope life cycle will help you to understand the interaction between scope and other AngularJS components.

The scope data goes through the following life cycle phases:

1. Creation

This phase initialized the scope. The root scope is created by the $injector when the application is bootstrapped. During template linking, some directives create new child scopes.

A digest loop is also created in this phase that interacts with the browser event loop. This digest loop is responsible to update DOM elements with the changes made to the model as well as executing any registered watcher functions.

2. Watcher registration

This phase registers watches for values on the scope that are represented in the template. These watches propagate model changes automatically to the DOM elements.

You can also register your own watch functions on a scope value by using the $watch() function.

3. Model mutation

This phase occurs when data in the scope changes. When you make the changes in your angular app code, the scope function $apply() updates the model and calls the $digest() function to update the DOM elements and registered watches.

When you do the changes to scope inside your angular code like within controllers or services, angular internally call $apply() function for you. But when you do the changes to the scope outside the angular code, you have to call $apply() function explicitly on the scope to force the model and DOM to be updated correctly.

4. Mutation observation

This phase occurs when the $digest() function is executed by the digest loop at the end of $apply() call. When $digest() function executes, it evaluates all watches for model changes. If a value has been changed, $digest() calls the $watch listener and updates the DOM elements.

5. Scope destruction

This phase occurs when child scopes are no longer needed and these scopes are removed from the browser’s memory by using $destroy() function. It is the responsibility of the child scope creator to destroy them via scope.$destroy() API.

This stop propagation of $digest calls into the child scopes and allow the memory to be reclaimed by the browser garbage collector.

Scope and Scope Inheritance

<!DOCTYPE html>
<html>
<head>
    <title>Scope and Scope Inheritance</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script>
        var parentApp = angular.module("myParentApp", []);

        parentApp.controller("MyParentController", function ($scope) {

            $scope.ParentName = 'Parent';

            $scope.Age = 50;

        });

        parentApp.controller("MyChild1Controller", function ($scope) {

            $scope.child1Name = 'Child-1';

            $scope.Age = 10;

            $scope.gender = 'M';

        });

        parentApp.controller("MyChild2Controller", function ($scope) {

            $scope.child2Name = 'Child-2';

            $scope.Age = 4;

            $scope.gender = 'F';

        });

    </script>

</head>

<body ng-app="myParentApp">

<h2>Scope Inheritance</h2>

<div ng-controller="MyParentController">

    <;p>{{ParentName}}

        <br/>{{Age}}

    <div ng-controller="MyChild1Controller">

        <p>{{child1Name}}

            &<br/>{{Age}}</p>

    </div>

    <div ng-controller="MyChild2Controller">

        <p>{{child2Name}}

            <br/>{{Age}}</p>

    </div>

</div>

</body>
</html>