Dirty check is mentioned in the $apply method. First, the apply method will trigger the evel method. When the evel method is parsed successfully, the digest method will be triggered, and the digest method will trigger the watch method.
(1)$watch introduction
When digest is executed, if the value observed by watch is different from the last execution, it will be triggered.
The watch inside AngularJS realizes the timely updating of the page with the model.
The $watch method is mainly used to manually monitor an object, but an event is triggered when the object changes.
(2)watch method usage
$watch(watchFn,watchAction,deepWatch)
watchFn: string of angular expression or function
watchAction (newValue, oldValue, scope): watchFn will be called when it changes
deepWatch: Optional Boolean value command checks whether each attribute of the monitored object changes
$watch will return A function. If you want to log out this watch, you can use the function
(3) Example
In the previous example, when the name form changes 30 times, an event is triggered.
The controller code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var firstController = function ($scope){ $scope.n ame='张三'; $scope.count=0; // 监听一个model 当一个model每次改变时 都会触发第2个函数 $scope.$watch('name',function(newValue,oldValue){ ++$scope.count; if($scope.count > 30){ $scope.name = '已经大于30次了'; } }); } Copy after login |
html code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p ng-app=""> <p ng-controller="firstController"> <input type="text" value="" ng-model="name"/> 改变次数:{{count}}-{{name}} </p> </p> <script type="text/javascript" src="app/index.js"></script> <script type="text/javascript" src="../../vendor/angular/angularjs.js"></script> </body> </html> Copy after login |
1234 |
123 |
The above is the detailed content of Detailed explanation of angular's $watch method. For more information, please follow other related articles on the PHP Chinese website!