首页 > 代码库 > angular js一$watch监控属性和对象

angular js一$watch监控属性和对象

$Watch:(监听一个model,当一个model每次改变时,都会触发第二个函数)

 

$watch(‘watchFn‘,watchAction,deepWatch)

watchFn带有Angular 表达式或者函数的字符串,它会返回被监控的数据模型的当前值。

watchAction: 一个函数function(newValue,oldValue){},当watchFn 发生变化时会被调用

deepWatch:默认为false,监听数组的某个元素或者对象的属性时设置为true;

 

监控一个属性

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
<div  ng-app="myApp" ng-controller="myCtrl">
    <form>
        <div class="form-group">
            <input  ng-model="name" />{{name}}
            <p>改变次数{{count}}</p>
        </div>
    </form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
   
    var app = angular.module(‘myApp‘, []);
    app.controller(‘myCtrl‘, function ($scope){
        $scope.name = ‘橘子‘;
        $scope.count = 0;
        $scope.$watch(‘name‘, function (newValue, oldValue) {
            $scope.count++;
            if($scope.count >5){
                $scope.name = ‘苹果‘;
            }
        });
    });
</script>
</body>
</html>

 

监控一个对象(deepWidth为true)

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
<div  ng-app="myApp" ng-controller="myCtrl">
    <form>
        <div class="form-group">
            <input  ng-model="Data.name" />{{Data.name}}
            <p>改变次数{{count}}</p>
        </div>
    </form>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">

    var app = angular.module(‘myApp‘, []);
    app.controller(‘myCtrl‘, function ($scope){
        $scope.Data = { name: ‘橘子‘ };
        $scope.count = 0;
        $scope.$watch(‘Data‘, function (newValue, oldValue) {
            if(newValue =http://www.mamicode.com/= oldValue)
            return;
            $scope.count++;
            if($scope.count >5){
                  $scope.Data.name = ‘苹果‘;
            }
        }, true);
    });
</script>
</body>
</html>

 

angular js一$watch监控属性和对象