The built-in method in Angular JS $watch

There is a dirty check in the $apply method. First, the apply method will trigger the evel method. When the evel method is successfully resolved, the digest method will be triggered, and the digest method will trigger the watch method.

$watch(watchFn,watchAction,deepWatch)

watchFn: String of angular expression or function

watchAction(newValue,oldValue,scope): watchFn changes will be called

deepWatch: optional boolean to check if every property of the monitored object has changed

$watch will return a function, if you want to unregister this watch, you can use the function

For example, implement a function that alerts you when the user name is modified more than five times

It should be noted that $watch only exists as a monitor and cannot prevent you from continuing to modify the value in the input.

angular.module('MyApp',[])
.controller('ParserController',function($scope){
    $scope.count = 0;
    $scope.$watch('name',function(newVal,oldVal){
        ++$scope.count ;
        if($scope.count > 5){
            alert("hahaha")
        }
    });
});

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <script src="../../src/angular.js"></script>
    <script src="parser.js"></script>
</head>
bodyapp<="MyApp">
    <div ng-controller="ParserController">
        <input ng-model="name">
    </div>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167309&siteId=291194637