One of the things we often need to do when writing an application with ANGULAJS is to monitor the variables in the model and respond accordingly to the changes that occur. ANGULARJS provides us with a very handy $watch method that helps us to monitor the variables in each scope. The following is a very simple example:
<!DOCTYPE HTML><HTMLNg-app><Head> <MetaCharSet= "Utf-8"> <title>2, Angularjs's $watch () method</title> <Scriptsrc=".. /js/angularjs.js "></Script> <Scriptsrc=".. /js/index7.js "></Script></Head><Body><!--ANGULARJS Data binding, two-way binding, binding between M,v,c - <DivNg-controller= "Firstcontroller"> <inputtype= "text"Ng-model= "Name"value="" /> <P>Number of changes: {{count}}---{{name}}</P> </Div></Body></HTML>
var firstcontroller=function($scope) { $scope. Name= "Zhang San"; $scope. Count=0; $scope. $watch ("name",function(newvalue,oldvalue) { console.log (newvalue,oldvalue); + +$scope. Count ; if ($scope. count>10) { $scope. Name= "Input has changed 10 times";};} );}
Inside Angularjs, every time we make a modification to the Name property of the Ng-model binding, Angularjs internal $digest runs once and checks what we use $watch to monitor after the run is done, and if and when the last $ Digest before the change, execute the handler function in which we bind.
Angularjs--watch () method