javascript - 如果在回调函数内部使用,范围不会更新

标签 javascript angularjs

基本上我在 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

http://jsfiddle.net/vj5D7/1/

最佳答案

这是人们使用 AngularJS 时遇到的常见问题之一。

setTimeout 不会触发$scope.$apply()。如果您使用 Angular 自己的 $timeout,它会为您完成此操作。

我发现您没有使用任何 $scope 变量。我不熟悉新的语法。

关于javascript - 如果在回调函数内部使用,范围不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23899608/

相关文章:

javascript - 在 JavaScript 或 jQuery 中是否有等效于 Python 的 all 函数?

javascript - Masonry 和 JQuery 重新加载

javascript - 在 JavaScript 中将用户输入元素输入到数组中

javascript - 使用 $ngresource promise Angularjs 填充选择标签

javascript - 在for循环中创建多维数组

javascript - jquery 在执行之前的事件之前等待 for 循环完成

javascript - AngularJS:如何将socket.io服务数据传递给相应的指令

angularjs - SSL 和谷歌浏览器不安全警告

javascript - 如何创建从不读取 $scope 的 $scope 函数?

angularjs - 对 ng-model 使用 <select> 的值和文本