Javascript 如果在回调函数内部使用,则不会更新作用域
基本上,我在控制器中有一个侦听器函数。调用此函数时,我想更新我的UI/范围,但它没有发生。这是我的密码: HTMLJavascript 如果在回调函数内部使用,则不会更新作用域,javascript,angularjs,Javascript,Angularjs,基本上,我在控制器中有一个侦听器函数。调用此函数时,我想更新我的UI/范围,但它没有发生。这是我的密码: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> </div> </div> 小提琴 这是人们对AngularJS的常见障碍之一 setTimeout不会触
<div ng-app="myApp">
<div ng-controller="MainCtrl as mainCtrl">
Main {{mainCtrl.foo}} <br/>
</div>
</div>
小提琴
这是人们对AngularJS的常见障碍之一 setTimeout不会触发
$scope.$apply()
。如果您使用angular自己的$timeout
,它会为您做到这一点
我看到您没有使用任何$scope变量。我不熟悉这种较新的语法。如果在角度摘要周期之外更新某些内容,则需要调用
$scope.$apply()
。为什么不使用$timeout
而不是setTimeout
。我建议使用纯angular,并且仅在特定情况下使用jQuery。我仅使用setTimeout作为示例,在我的示例中,我正在侦听来自外部服务(chrome消息传递)的消息
var myApp = angular.module('myApp', []);
var my = {};
my.MainCtrl = function() {
this.foo = 'waiting';
this.notifier = new other.Notifier();
this.notifier.addListener(this.update.bind(this));
}
my.MainCtrl.prototype.update = function() {
this.foo = 'updated';
alert('Updated');
}
// register all controllers
myApp.controller('MainCtrl', my.MainCtrl);
var other = {};
other.Notifier = function() {
};
other.Notifier.prototype.addListener = function(callback) {
setTimeout(callback, 1000);
};