Search This Blog

2016-01-11

Angular JS Tutorial8: $digest and $watch

$digest() is useful when we want to hook up a vanilla javascript in angularjs.

When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object. The framework is "watching" the variable. Watches are created using the $scope.$watch() function


<!DOCTYPE html>
<html lang="en" >
<head>
 <title>$digest,$watch</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

 <script type="text/javascript">
  var application=angular.module('myapp',[]);
  application.controller('mycontroller',function($scope)
  {
   $scope.myRandomNumber=Math.random();
   $scope.counter=-1;
   document.querySelector('input').addEventListener('click',function(){
    $scope.myRandomNumber=Math.random();
    $scope.$digest();
    $scope.$watch('myRandomNumber',function(newValue,oldValue)
    {
     if($scope.counter==5)
      alert('You reach at 5');
     $scope.counter++;
    }
    );
   },false);
  }
  );
 </script>
</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{myRandomNumber}}
 <br/>
 <input type="button" value="Generate Random Number"/>
</body>
</html>


No comments: