$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> <input ng-model="name" />{{name}} <p>改变次数{{count}}</p> </div> </form> </div> <script src="https://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> <input ng-model="Data.name" />{{Data.name}} <p>改变次数{{count}}</p> </div> </form> </div> <script src="https://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 == oldValue) return; $scope.count++; if($scope.count >5){ $scope.Data.name = '苹果'; } }, true); }); </script> </body> </html>

以上这篇关于angular js_$watch监控属性和对象详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypjzg.html