Total Pageviews

Wednesday 13 March 2019

Digest Cycle | AngularJS


Digest Cycle

We can consider digest cycle as a loop in which AngularJS checks if there are any changes to the variables watched by respective $scope’s. If we want to monitor the changes of a variable then we can mark them for being watched.  This process is called as digest cycle or loop.

The good thing is that, everything attached to the scope is not being watched; else it would have been a serious performance issue as digest cycle loop through the variables to check the changes.

$watch(), $digest() and $apply()
are the AngularJS $scope functions.


Use $watch to listen for $scope changes

There are 2 ways to watch a scope variable.

1)   via expression <span>{{ clientId}}</span>
2)   via the $watch service

To explain first point, Expressions “{{}}” creates a watch in the background. And AngularJS directives (such as ng-repeat) can also create implicit watches.

To explain second point, we can also create custom watches. $watch service helps to run any code when any value attached to the $scope has changed. It is not recommended to use explicit watches but sometimes it is helpful.

For instance, if we want to run some code each time ‘clientId’ changes, we could do the following:

function clientController($scope) {

    $scope.clientId = 1;

    $scope.$watch('clientId ', function() {
        alert(‘clientId has changed!');
    });

    $scope.buttonClicked = function() {
        $scope.clientId = 2; // This will trigger $watch expression to kick in
    };
}

Use $apply to make changes with the digest cycle

Sometimes we need to set a variable value on completion of a particular task. But AngularJS can't wait for this to happen, since it hasn't been instructed to wait on anything.

To avoid this scenario, $apply has been introduced. It is used to execute the desired code, and after that $scope.$digest() is called, so all watches are checked and their corresponding listener functions are called.

However, $scope.$digest() should only use to integrate with other code, but not with regular AngularJS code, as AngularJS will throw an error then. The $digest() function triggers the data binding to HTML view.


2 comments:

  1. The amazing features on the Disney Princess Girls bike makes it unique. There are a lot of girls bikes on the market at present, so be sure to do your research. It is well designed to fit every little girl's comfort and safety. For every girl's first bike, parents wanted the best for their little girl and the Disney Princess Girls bike has that. bike decal

    ReplyDelete

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...