An Introduction To Angular’s Digest Cycle

Before starting off, let’s play a quiz!

Name the structural framework used for dynamic web apps? What is that framework that grants you with the access to use HTML as your template language and even allows you to extend the HTML’s syntax in order to express your application’s components clearly and in a brief manner? Yes, you guessed it right. It is none other than AngularJS!

I’ve been working on Angular.js for a few years and let me declare that it is one of the most exciting and fantastic frameworks to work on. The best thing about this framework is that it has data binding and dependency injection capability that tends to eliminate much of the code, thus eliminating the use of writing it on your own. And it all happens within the browser application for making it an ideal partner with any server technology!

AngularJS provides and offers an incredibly awesome feature known as two-way data binding which greatly simplifies our lives. Data binding means that when you change something in the view, angular controller the scope model automagically updates. Similarly, whenever the scope model gets changes, the view updates itself with the new value due to scope only which is done by the watcher in AngularJS it is also known as a part of digest cycle process.

Now the question that arises is that what is the process of AngularJS? An expression ({expression}), behind the scenes Angular automatically sets up a watcher on the scope model, which in turn updates the view whenever the model changes. This watcher is just like any watcher you set up in AngularJS this whole process is a unit of  angular digest cycle process:

The Need For Digest Process

angular-digest-process

Let’s begin with why digest is in the first place?

AngularJS solves the problem of synchronization between a data model. But the point is that how and when the data model will get change? The process of changing track is done by the watcher in Angular. Watchers are responsible to track the changes is being in the scope variable and the value in AngularJS. I would like to take you in the depth of the digest process of When it takes place? and How it works? and How can we implement this?

Before all this, first, we need to understand about $watch functionality, what it is actually and how it works?

A Brief To $watch()

Angular.JS is that which uses a concept of a watcher and a listener.

watch

A Watcher is a function that returns a value being watched for a scope. Most often these values are the properties of a data model that has to be watched. But it doesn’t always have to be model properties — we can track component state on the scope, computed values, third-party components etc with the help of watchers. If the returned value is different from the previously returned value of a scope, angular calls a listener. This listener is usually used to update the UI. The $scope.watch() is used to track the scope variable and their value. When you register a watch you pass two functions as parameters to the $watch() function:

  • Angular value function
  • Angular  listener function

Here is an example for Watcher:

$scope.$watch(function() {
                          },
              function() {
                          }
             );

The above function is the value function and the below-given function is the listener function.

The above value function should return the value which is being watched for the scope. Then AngularJS can further check that the value is being returned against the value the watch function returned the last time. This is the way AngularJS can determine if the value has been changed. Here is an example:

$scope.$watch(function(scope) { 
                   return scope.data.myVar },
              function() {
              }
             );

This example value function returns the $scope variable scope.data.myVar. If the value of this variable keep tracking gets changes, a different value will be returned, then that time it calls to the listener function.

Notice how the value function use to the scope as a parameter (without the $ in the name) in AngularJS during the digest cycle process. Via this parameter, the value function can access the $scope and its variables. The value function automatically watches global variables instead if you need that, but mostly you will watch a $scope variable.

The listener function should do whatever it needs to do if the value has changed at any point. Whether you need to change the content of another variable or set the content of an HTML element or something else., here is an example for it:

$scope.$watch(function(scope) { return scope.data.myVar },
              function(newValue, oldValue) {
                  document.getElementById("").innerHTML =
                      "" + newValue + "";
              }
             );

This example sets the inner HTML of an HTML element with the new value of the variable, embedded in the element which makes the value bold during execution of above example. Yes, you could have done this using the code expression {{ data.myVar }, but this is just an example of what you can do inside the listener function this is the alternate process to do that. ”””

Below is the example of watchers, explaining its working?

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
https://code.angularjs.org/1.2.9/angular.min.js

    angular.module('myApp', [])
        .run(function($rootScope){
            var $scope = $rootScope;
            $scope.$watch('enabled', function(val) {
                console.log('You are now: ' + (val ? 'enabled' : 'disabled'));
            });
            $scope.enabled = true;
            $scope.enabled = false;
            $scope.enabled = 1;
        })

<body>
    <p ng-if="enabled">Enabled</p>
    <button ng-click="enabled=!enabled">Click!</button>
</body>
</html>

On Execution of above code, you will see that the behavior is in line with examples you’ve come across before. Initially, there was an “enabled” paragraph because $scope.enabled is initially set to true. Use the ng-click event on the button to toggle $scope.enabled’s value. When $scope.enabled gets toggled to false, the paragraph text gets removed from the rendered view.

Watchers are existing in AngularJS app work for digest cycle. This process is really a function that repeatedly checks for changes in the variable and their values for a scope ‘watchers’ we have. As per digest cycle process, with every scope watcher you create, a corresponding watcher function for that particular scope will be added to the digest loop at the same time itself. This function executes automatically every time the cycle runs, comparing the watcher’s old value with its new value. The cycle runs once to check for initial changes, and then a second, third, fourth time until all watchers stop changing this whole process is known as the digest cycle process.

As we all know Angular having the two-way binding process, this is done by the digest cycle which makes two-way data binding possible in Angular 1. It’s also what causes the majority of Angular 1’s performance issues. It should be noted that the digest cycle runs every time the app’s state changes. You may see the $digest() or $apply() functions used.

Concluding Words

I hope after reading this blog you will come to know what exactly the digest process is. The most important thing to keep in mind during the process of detecting changes is whether or not Angular can detect your changes anyhow. If it is not being watched, then you must call $apply() manually so you will be able to find out what changes having the scope.

Keep reading for more such updates!

Leave a Comment