关于angular js_$watch监控属性和对象详解
程序员文章站
2022-05-14 20:45:10
$watch:(监听一个model,当一个model每次改变时,都会触发第二个函数)
$watch('watchfn',watchaction,deepwatch)
w...
$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 == oldvalue) return; $scope.count++; if($scope.count >5){ $scope.data.name = '苹果'; } }, true); }); </script> </body> </html>
以上这篇关于angular js_$watch监控属性和对象详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: Angular组件化管理实现方法分析
下一篇: JAVA集合篇---详细