AngularJS - $watch无法按预期工作
AngularJS - $watch not working as expected
这是我的应用程序.js
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyController', ['$scope', function($scope){
$scope.watchMe = 'hey';
$scope.init = function() {
setTimeout(function() {
$scope.watchMe = 'changed!';
}, 3000)
};
$scope.$watch('watchMe', function() {
console.log($scope.watchMe)
});
}]);
我想,3秒钟后,我会看到:
'changed!'
在我的控制台中。
相反,我只是看到:
'hey'
我在 index.html 中调用我的 init(( 函数,如下所示:
<div ng-controller="MyController" ng-init="init()">
为什么我会看到此输出?
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyController', ['$scope', '$timeout', function($scope, $timeout){
$scope.watchMe = 'hey';
$scope.init = function() {
$timeout(function() {
$scope.watchMe = 'changed!';
}, 500);
};
$scope.$watch('watchMe', function(newVal, oldVal) {
console.log(newVal);
});
}]);
您正在使用 setTimeout 方法。Angular没有关注那个事件。使用$timeout Angular 的服务,然后您可以看到预期的结果。
阅读有关角度摘要循环和脏检查的信息,了解更多详细信息。
相关文章:
- 为什么AngularJS$scope.watch()在我告诉它监视数组时会停止工作
- 使用服务跟踪用户状态并使 $watch() 正常工作
- AngularJS - $watch无法按预期工作
- AngularJS$watch在if块中不工作
- angularJS$watch在使用控制器更新数据时不在指令中工作
- Greasemonkey脚本停止工作,出现错误:unsafeWindow.document.watch不是函数
- Angular:控制器和指令之间的共享数据.$watch是如何工作的
- $watch不能在其他控制器的变量上工作
- Angularjs: $watch不能在ngTable的控制器中工作
- 使用grunt-contrib-watch对两个目录进行深度的单向同步.代码可以工作,但是grunt-contrib-w
- Angularjs $watch无法正常工作
- Ionic, AngularJs:指令属性$watch在视图被渲染后停止工作
- 当grunt-contrib-watch与grunt-express结合使用时,浏览器负载不工作
- 为什么$watch()不能工作?
- Gulp-inject不能和gulp-watch一起工作
- AngularJS自定义指令$watch不工作
- ng-单击值更改 + $scope.watch 绑定无法正常工作
- $scope上的ng类.$watch不工作在第二次点击
- $watch不能在Angular Modal中工作
- $watch不能与数据模型工厂一起工作