<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div ng-app> <div ng-controller="firstController"> <input type="text" value="" ng-model="name"> 改变次数:{{count}}--{{name}} </div> </div> <script type="text/javascript" src="app/index.js"></script> <script type="text/javascript" src="../../vendor/angular/angularjs.js"></script> </body> </html>
var firstController = function ($scope) { $scope.name = ‘Alrale‘; $scope.date = { name : ‘Alrale‘, count : 20 } $scope.count = 0; //当 model 每次改变时,都会触发第2个函数 $scope.$watch(‘name‘,function (newValue,oldValue) { console.log(newValue); ++$scope.count; if($scope.count > 30){ $scope.name = ‘已大于30次‘; } }) $scope.$watch(‘date‘,function () { // $scope.$watch(‘date.name‘,function(){}) },true) }
- Angular 内部的 watch 实现了页面的 model 的及时更新。
- $watch(watchFn, watchAction, deepWatch)
watchFn: angular 表达式或函数字符串;
watchAction(newValue, oldValue, scope): watchFn 发生变化时会被调用;
deepWatch: 可选的布尔值命令检查被监控的对象的每个属性是否发生变化。
时间: 2024-10-14 01:36:37