$watch()
<!doctype html>
<html ng-app="watchModule">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../angular-1.5.5/angular.js">
</script>
</head>
<body>
<input ng-model='num' type='number'/>
<div>change count: {{count}}</div>
<script>
angular.module('watchModule',[])
.run(['$rootScope',function($rootScope){
$rootScope.count = 0;
$rootScope.num = 100;
var unbindWatcher= $rootScope
.$watch('num',function(newValue,oldVaule){
if(newValue == 2){
unbindWatcher();
}
$rootScope.count++;
})
}]);
</script>
</body>
</html>
当我们使用类似如下代码时:
<input id="input" type="text" ng-model="name"/>AngularJS框架会在幕后为我们在$scope中设置一个watcher,用来在数据发生变化的时候更新view,这里的watcher跟前面讲的手动调用的$watch()方法所添加的watcher是一样的
<div id="output">{{name}}</div>
$digest
在有些情况下,模型数据修改后需要手动调用$apply()方法来触发$digest循环,例如使用JS的setTimeOut()方法来更新一个模型数据,AngularJS框架就没办法知道我们修改了什么,也就无法触发$digest循环了。
修改前:
<!doctype html>
<html ng-app="msgModule">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../angular-1.5.5/angular.js">
</script>
</head>
<body>
<div ng-controller="MsgController">
<div>
<button ng-click="scheduleTask()">3秒后回显信息
</button>
</div>
<div>
{{message}}
</div>
</div>
<script>
angular.module('msgModule',[]).controller('MsgController',
function($scope) {
$scope.scheduleTask = function() {
setTimeout(function() {
$scope.message = '信息内容';
console.log('message='+$scope.message);
}, 3000);
}
});
</script>
</body>
</html>
修改后
<!doctype html>
<html ng-app="msgModule">
<head>
<meta charset="UTF-8">
<title>ch05_11</title>
<script type="text/javascript" src="../angular-1.5.5/angular.js">
</script>
</head>
<body>
<div ng-controller="MsgController">
<div>
<button ng-click="scheduleTask()">3秒后回显信息
</button>
</div><br/><br/>
<div>
{{message}}
</div>
</div>
<script>
angular.module('msgModule',[]).controller('MsgController',
function($scope) {
$scope.scheduleTask = function() {
setTimeout(function() {
$scope.$apply(function(){
$scope.message = '信息内容';
console.log('message='+$scope.message);
});
}, 3000);
}
});
</script>
</body>
</html>
<!doctype html>
<html ng-app="msgModule">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../angular-1.5.5/angular.js">
</script>
</head>
<body>
<div ng-controller="MsgController">
<div>
<button ng-click="scheduleTask()">3秒后回显信息
</button>
</div><br/><br/>
<div>
{{message}}
</div>
</div>
<script>
angular.module('msgModule',[]).controller('MsgController',
function($scope,$timeout) {
$scope.scheduleTask = function() {
$timeout(function() {
$scope.message = '信息内容';
console.log('message='+$scope.message);
}, 3000);
}
});
</script>
</body>
</html>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。