Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between $watch and $digest in angularjs

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 787
    Comment on it

    The angularjs $watch, $digest and $apply are essential parts. You must know the difference between them. Here we are going to discuss them.

    $watch():
    In Angular, you often need to do data binding to modify data. When you do some data binding on $scope to your view, AngularJS creates a watch. That means watch looks for change in variable on $scope object.  The AngularJS framework watches a variable using $scope.$watch() function. When you create a watch, there are two parameters passed:
    1. value function
    2. listener function

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


    The value function returns the value that is being watched by $watch function. This is how it can check the value returned to the last value. If the value is changed, then listener function is called. Then you can do whatever you want to listener function.

    $digest():
    $scope.$digest() function runs in a loop over all the watches that are created by angular. It will call the listener function if the value is changed in the scope object.

    $apply():
    $scope.$apply() is used to execute a function as a parameter and after that $digest() function is called. That means all the watches are checked that are created and the data binding is refreshed.

    Here is an example:

    <div ng-controller=newController">
        {{data.time}}
    
        <br/>
        <button ng-click=refresh()>refresh time - ng-click</button>
        <button id=refreshButton  >refresh time</button>
    </div>
    
    
    <script>
        var module       = angular.module(demoApp, []);
        var newController1 = module.controller("newController", function($scope) {
     
            $scope.data = { time : new Date() };
    
            $scope.refresh = function() {
                $scope.data.time = new Date();
            }
    
            document.getElementById("refreshButton")
                    .addEventListener('click', function() {
                console.log(refresh time clicked");
                $scope.data.time = new Date();
            });
        });
    </script>
    
    

 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: