AngularJS promise 在完成时不会调用 `then` 回调

标签 angularjs promise q

我有一个类似主 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'
      });
  });
});

<强> Example on jsfiddle with jQuery ajax

关于AngularJS promise 在完成时不会调用 `then` 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174965/

相关文章:

javascript - 通过 ng-click 更改颜色

javascript - Angular 未知提供者

node.js - 自动解决后的 promise 链接

node.js - Node.js 中作业执行后返回 Promise

javascript - promise 后的返回值

angularjs - AngularJS 中指令隔离范围与 ng-repeat 范围

javascript - 为什么在第一个 Promise 解析之后执行链式 Promise 后排队的微任务而忽略链式 Promise?

javascript - 带有 typescript require 和 .d.ts 文件的 Node.js

javascript - done() 与 bluebird 的 spread() 之间的区别

angularjs - 在 AngularJS 中动态加载 Controller 以进行路由