基本上我在 Controller 中有一个监听器函数。当调用此函数时,我想更新我的 UI/范围,但它没有发生。这是我的代码:
HTML
<div ng-app="myApp">
<div ng-controller="MainCtrl as mainCtrl">
Main {{mainCtrl.foo}} <br/>
</div>
</div>
JS
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);
};
fiddle
最佳答案
这是人们使用 AngularJS 时遇到的常见问题之一。
setTimeout 不会触发$scope.$apply()
。如果您使用 Angular 自己的 $timeout
,它会为您完成此操作。
我发现您没有使用任何 $scope 变量。我不熟悉新的语法。
关于javascript - 如果在回调函数内部使用,范围不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23899608/