The $watch () in Angularjs, $digest () and $apply () differentiate _angularjs

Source: Internet
Author: User


Angularjs $scope inside the $watch (), $digest () and $apply () are the core functions of ANGULARJS, learning Angularjs must understand these functions.



When you bind a variable in $scope to view, Angularjs automatically creates a "Watch" inside it. "Watch" is used to monitor the change of variables in the ANGULARJS scope. You can create "watch" by calling the $scope. $watch () method.



$scope. The $digest () function iterates through all the watches and detects whether the variables in the $scope they are listening to change. If the variable changes, the listener function corresponding to the variable is invoked. Listening functions can do many things, such as letting the text inside HTML display the latest variable values. Visible, $scope. $digest can trigger data-binding updates.



In most cases, ANGUALRJS will automatically invoke the $scope. $watch () and $scope. $digest () functions, but in some cases we need to call them manually, so it is necessary to understand how they work.



$scope. $apply () This function executes some code before calling $scope. $digest (). All watches will be detected once and the corresponding listener function will be executed. $scope. $apply () is useful when ANGULARJS is integrated with other JavaScript code.



Next we explain specifically the $watch (), $digest () and $apply ().



$watch ()
$watch (watchexpression, Listener, [objectequality])



Watchexpression: Listener object, can be string or function (scope) {}



Listener: callback function function (Newval,oldval,scope) {} that is executed when the listener object changes



Objectequality: Depth listening, if set to true, tells angular to check for changes to each property in the object being monitored. If you want to monitor the individual elements of an array or the properties of an object rather than an ordinary value, you should use it. (default value: false)



$digest ()
detects the current scope and all watches in the child scope, because the listener modifies model (variable in scope) during execution, $digest () is called until the model does not change. When the call is over 10 times, the $digest () throws an exception "Maximum iteration limit exceeded" to prevent the program from entering a dead loop.



$apply ()
$apply ([exp])



Exp:string or function (scope) {}



The $apply () life cycle pseudo code diagram is as follows


function $apply(expr) {
 try {
  return $eval(expr);
 } catch (e) {
  $exceptionHandler(e);
 } finally {
  $root.$digest();
 }
}


Example
Here's an example to illustrate $watch, $digest and $apply.


<script>
var module = angular.module("myapp", []);
var myController1 = module.controller("myController", function($scope) {
  $scope.data = { time : new Date() };
  $scope.updateTime = function() {
    $scope.data.time = new Date();
  }
   
  document.getElementById("updateTimeButton")
      .addEventListener('click', function() {
    console.log("update time clicked");
    $scope.data.time = new Date();
  });
});
</script>
<body ng-app="myapp">
<div ng-controller="myController">
  {{data.time}}
 
  <br/>
  <button ng-click="updateTime()">update time - ng-click</button>
  <button id="updateTimeButton" >update time</button>
</div>
</body>


This code is bound $scope.data.time to HTML, and the binding automatically creates a watch to listen for $scope.date.time changes. In addition, there are 2 buttons, the first button is through Ng-click directive to invoke the $scope.updatetime method, Angularjs will automatically execute the $scope. $digest () to display the most recent time in HTML. The second button is to update the time in the HTML by adding a click event through the JavaScript code. But the second button is not working, and its solution is to manually invoke the $scope $digest () method at the end of the click event, as follows:


document.getElementById ("Updatetimebutton")
    . AddEventListener (' click ', Function () {
  console.log ("Update Time clicked ");
  $scope. data.time = new Date ();
  $scope. $digest ();
});


Another solution is to call the $scope. $apply (), as follows:


document.getElementById ("Updatetimebutton")
    . AddEventListener (' click ', Function () {
  $scope. $apply ( function () {
      console.log ("Update Time clicked");
      $scope. data.time = new Date ();
    });



The above is the entire content of this article, I hope to help you learn.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.