Sah*_*bin 20 javascript angularjs
我正在使用angularJS 1.4.8,昨天我注意到$ scope.$ watch不会触发每次导致我的应用程序错误的更改.
有没有办法迫使它立即对每一个变化起作用?就像在这段代码中一样,在消息的每一次更改中,我希望watch中的函数触发:
(function(){
angular.module('myApp', [])
.controller('myAppController', myAppController)
function myAppController($scope){
console.log('controller loading !');
$scope.message = 'message1';
$scope.$watch('message', function(newMessage){
console.log('newMessage', newMessage)
});
function changeMessage(){
$scope.message='hi';
$scope.message='hi12';
}
changeMessage();
}
})();
Run Code Online (Sandbox Code Playgroud)
控制台将打印:
controller loading !
newMessage hi22
Run Code Online (Sandbox Code Playgroud)
plunker链接https://plnkr.co/edit/SA1AcIVwr04uIUQFixAO?p=preview
编辑:我真的想知道是否有任何其他方法,而不是包装更改与超时和使用范围适用,在我的原始代码iv'e多个地方,我改变范围属性,我想避免使用这每一个更改.
更新你的changeMessage函数,以便它使用$ scope.$ apply函数,它将确保反映你的更改,并且angular知道你对变量的更改.
changeMessage() {
setTimeout(function () {
$scope.$apply(function () {
$scope.message = "Timeout called!";
});
}, 2000);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2223 次 |
| 最近记录: |