Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果在回调函数内部使用,则不会更新作用域_Javascript_Angularjs - Fatal编程技术网

Javascript 如果在回调函数内部使用,则不会更新作用域

Javascript 如果在回调函数内部使用,则不会更新作用域,javascript,angularjs,Javascript,Angularjs,基本上,我在控制器中有一个侦听器函数。调用此函数时,我想更新我的UI/范围,但它没有发生。这是我的密码: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> </div> </div> 小提琴 这是人们对AngularJS的常见障碍之一 setTimeout不会触

基本上,我在控制器中有一个侦听器函数。调用此函数时,我想更新我的UI/范围,但它没有发生。这是我的密码:

HTML

<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);
};