Open In App

Explain AngularJS Scope Life-Cycle

In AngularJS, The Scope acts as a merging parameter between the HTML and Javascript code, ie, it is the binding part between view and controller and it is a built-in object. It is available for both the view and the controller. It is used to define inside the controller, in order to define the member variables. It has variables that are the application data and methods.

Rootscope: It is a scope that is created on the HTML element which has the ng-app directive & is contained in all the applications. The availability of root scope is in the whole application. 



The life cycle defines the journey of the application, which it goes through, right from creation to destruction. The lifecycle of AngularJs determines how the data interacts with AngularJS. Understanding the lifecycle enables the developer to more efficiently develop applications with greater code reusability and maintainability. During the lifecycle, all these components are monitored and governed by AngularJs itself. It allows the developers to maintain and update the components and code, while it goes through the creation to destruction phase.

In the flow of code in Javascript, the javascript callback will be executed for the corresponding event received by the browser. After that, when the callback gets completed, the DOM objects will be re-displayed by the browser. AngularJS remain unaware of the changes in the model if any javascript code, that is executed outside the context of AngularJS, by the browser. For this, AngularJS $apply API is used, in order to detect the model change.



Importance of Scope lifecycle:

AngularJS Scope Lifecycle: The lifecycle of scope in AngularJS is as follows:

Example 1: This example describes the creation of the Scope Lifecycle in AngularJS.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <h1>GeeksForGeeks </h1>
    <h3>Explain AngularJS scope lifecycle </h3>
    <p>RootScope's name is:</p>
    <h1>{{name}}</h1>
    <div ng-controller="myCtrl">
        <p>Scope's name is:</p>
        <h1>{{name}}</h1>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.run(function ($rootScope) {
            $rootScope.name = 'Alex';
        });
        app.controller('myCtrl', function ($scope) {
            $scope.name = "Chris";
        });
    </script>
</body>
  
</html>

Output:

 

 Syntax of watch():

$scope.$watch('expression', function (newvalue, oldvalue) {
    // Your Code
});

Example 2: This example describes the Watcher Registration in AngularJS.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <h1> GeeksForGeeks </h1>
    <h3> Explain AngularJS scope lifecycle </h3>
    <div ng-app="watchApp" 
         ng-controller="watchCtrl">
         Enter the text:
         <input type="text" 
                ng-model="txtval" />
                <br /><br />
        <span style="color:Red">
            No. of Times $watch() Function Fired: {{count}}
          
    </div>
    <script type="text/javascript">
        var app = angular.module('watchApp', []);
        app.controller('watchCtrl', function ($scope) {
            $scope.count = -1;
            $scope.$watch('txtval', function (newval, oldval) {
                $scope.count = $scope.count + 1;
            });
        });
    </script>
</body>
  
</html>

Output: From the output, we see no. of times changes are made in the text and thus how $watch monitors code and returns or generates the output.

 

Example 3: This example describes the Model Mutation in AngularJS.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <div ng-app="digestApp" 
         ng-controller="digestCtrl">
        <h1> GeeksforGeeks </h1>
        <h3> Example of $digest() function </h3>
        <input type="button" 
               value="Click to Update DateTime"
               ng-click="updatedtime()" />
        <input type="button" 
               value="Click to Update DateTime forcefully." 
               id="btndigest" />
        <br /><br />
        <span style="color : Green">
            Current Date Time: {{currentDateTime | date:'yyyy-MM-dd HH:mm:ss'}}
          
    </div>
    <script type="text/javascript">
        var app = angular.module('digestApp', []);
        app.controller('digestCtrl', function ($scope) {
            $scope.currentDateTime = new Date();
            $scope.updatedtime = function () {
                $scope.currentDateTime = new Date();
            }
            var event = document.getElementById("btndigest");
            event.addEventListener('click', function () {
                $scope.currentDateTime = new Date();
                $scope.$digest();
            });
        });
    </script>
</body>
  
</html>

Output:

 

Example 4: This example describes the Mutation Observation & Scope Destruction in AngularJS.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body ng-app="myApp">
    <h1>GeeksForGeeks </h1>
    <h3> AngularJS scope lifecycle </h3>
    <div ng-controller='test' 
         ng-if="toggle">
        <button ng-click='dispatch()'>
              EVENT
          </button>
    </div>
    <button ng-click='toggle = !toggle'>
        Click to add / remove an event
    </button>
  
    <script>
        var myApp = angular.module('myApp', []);
        var startingDate = (new Date()).getTime();
        myApp.controller('test', function ($scope) {
  
            // Date controller was created
            var controllerDate = (new Date()).getTime() - startingDate;
            console.log('Controller created at ', controllerDate);
  
            // Listener that logs controller date
            $scope.$on('dispatched', function () {
                console.log('listener created at:', controllerDate);
            });
              
            // Function to dispatch event
            $scope.dispatch = function () {
                $scope.$emit('dispatched');
            };
            $scope.$on('$destroy', function () {
                console.log('Controller ', controllerDate, ' destroyed');
            });
        });
    </script>
</body>
  
</html>

Output:

 


Article Tags :