Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • $watch() , $digest() and $apply() in AngularJS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 454
    Comment on it

    There is an important concept of angularjs $scope function like:

    1. $watch
    2. $digest 
    3. $apply 

    As to understand angularjs more better we have to go throught the central function in angularjs.

    Lets discuss them one by one:

    1. $watch : A watch is called when there is any change in the $csope object. The watched are created using the $scope.watch() function.

    2. $digest : After that angularjs call the $digest function and it is used to itrate all the watches and it checks if there is any change in the watched variable and if there is any change then it call the listener function and the listener function change the html text and replace the old value with the new one.

    3. $apply : This is used to execute code and then it calls the $digest function. So all the watched are checked and corresponding listener function are called. The apply function is useful when integrating angularjs with other code.

    In most cases angularjs calls the $watch and $digest function internally. but we can manually do the same. so lets discuss it:

    1. $watch : When we register a watch manually we pass two functions as parameters to the $watch() function:
    a. Value function
    b. listener function

    Example:

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

    In this, the first one is the value and the second one is the listener function.

     

    Example:

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

     

    2. $apply : It take function as a parameter which is executed and after that $digest is called internally that makes it easier for us to make sure that all the watched has been checked so that all the binding  refreshed.

    Example

    $scope.$apply(function() {
        $scope.data.demo = "first value";
    });

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: