我有一个类似主 Controller 的东西,它在范围内设置一些东西,所以内部 Controller 可以使用它。
该设置工作是异步的,所以我将它包装在一个 promise 中,但除非它已经解决,否则它不会执行它的回调(我尝试设置一个断点,如果我等待足够长的时间,它实际上会运行 then
回调)。
这是一个 fiddle ,它通过超时而不是网络请求重现了我的问题:http://jsfiddle.net/LMv8v/1/
HTML
<div ng-app>
<div ng-controller="configController">
<div ng-controller="testC">
{{test}}
{{foo}}
</div>
</div>
</div>
Javascript
function configController ($scope, $q) {
var deferred = $q.defer();
$scope.config = deferred.promise;
setTimeout(function() {
console.log('timeout');
deferred.resolve({
'foo' : 'baz'
});
}, 1000);
};
function testC($scope) {
$scope.test = 'I am working, uh?';
$scope.config.then(function(config) {
console.log('then...');
$scope.$apply(function() {
$scope.foo = config.foo;
});
});
};
它显示“超时”,但不显示“then...”消息。
(我知道这更适合服务,但我已经有大量具有嵌套作用域的代码,我希望在开始重构之前使其正常工作)
最佳答案
如果您使用的是$.getJSON()
(我猜是来自 jQuery)
您在解决 Angular 世界之外的问题时会遇到类似的问题,请尝试以下操作。
$.getJSON('ajax/test.json', function(data) {
$scope.$apply(function(){
deferred.resolve({
'foo' : 'baz'
});
});
});
关于AngularJS promise 在完成时不会调用 `then` 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174965/