var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.form = {
name: 'my name',
age: '25'
}
$scope.$watch('form', function(newVal, oldVal){
console.log(newVal);
},true);
$scope.foo= function(){
$scope.form.name = 'abc';
$scope.form.age = $scope.form.age++;
}
$scope.foo();
$scope.bar= function(){
$scope.form.name = 'xyz';
$scope.form.age = $scope.form.age++;
}
$scope.bar();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">{{form}}<br>
<label>Name:</label> <input type="text" ng-model="form.name"/><br>
<label>Age:</label> <input type="text" ng-model="form.age"/> </div>
在控制器中,我四次更改了“form”对象属性,但 $watch 没有触发。从用户界面(输入)如果我改变它的工作原理
您的情况是,我认为在所有快速更新期间,角度摘要周期没有时间通过。
以下是一些参考资料,可以帮助您更多地了解 Angular 1.X 的摘要循环:
-
https://www.thinkful.com/projects/understanding-the-digest-cycle-528/ https://www.thinkful.com/projects/understanding-the-digest-cycle-528/
https://www.ng-book.com/p/The-Digest-Loop-and-apply/ https://www.ng-book.com/p/The-Digest-Loop-and-apply/
防止此类行为;您可以使用 $timeout (具有 $apply)依赖项强制摘要通过:https://docs.angularjs.org/api/ng/service/ https://docs.angularjs.org/api/ng/service/$timeout
例子:
$timeout(function(){
$scope.form.name = name;
$scope.form.age = $scope.form.age++;
})
我创建了一个 jsfiddle 来说明你的情况:
http://jsfiddle.net/IgorMinar/ADukg/ http://jsfiddle.net/IgorMinar/ADukg/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)