【问题标题】:How can I get a deferred object set in one scope to be included in the digest of another scope in AngularJS?如何将一个范围内的延迟对象集包含在 AngularJS 中另一个范围的摘要中?
【发布时间】:2012-11-21 18:48:43
【问题描述】:

伙计们,我有一个问题。我正在使用 AngularJS,并且在 Angular 服务定义中设置了一个延迟对象:

angular.module('myServices', []).
  service('Brand', function($rootScope, $q){
    var service = {
        getNext: function() {
            var deferred = $q.defer();

            setTimeout(function() {
                deferred.resolve('foo');
            }, 2000);

            return deferred.promise;
        }
    };

    return service;
});

该服务在我的控制器中使用:

angular.module({
    controllers: {
        brand: function($scope, Brand) {
            $scope.changeBrand = function() {
                $scope.brand = Brand.getNext();
            }
        }
    }
}, ['myServices]);

最后,视图等待 promise 被解析,然后显示它:

<a ng-click="changeBrand()" id="changeBrand">Change</a>
<p ng-bind="brand"></p>

问题在于,虽然 promise 正在解决,并且视图在等待 promise 被解决并显示结果时做得很好,但它并没有立即执行。它仅在我添加此代码并单击链接时显示:

// View:
<a ng-click="apply()">Apply</a> 

// Controller:
$scope.apply = function() {
    $scope.$apply();
};

promise 所在的摘要部分是否与视图/控制器范围更改时运行的摘要分开存在?当延迟解析时,如何让摘要自动在视图/控制器的范围内运行?

谢谢!

【问题讨论】:

    标签: javascript scope angularjs digest deferred


    【解决方案1】:

    几天前,我在使用 Promise 实现惰性控制器时遇到了同样的问题。当您查看有关 routeProvider 的文档时,有一个示例使用带有承诺的 $timeout 服务 (https://github.com/angular/angular.js/blob/master/src/ng/route.js#L186)。 $timeout 实施使用 $rootScope.$apply() 来调用生命周期并刷新绑定(AFAIK 它调用所有脏检查函数——这就是绑定在 Angular 中的工作方式)。所以解决我的问题(我认为也是你的问题)的解决方案是在 resolve() 之后添加 $rootScope.$apply(),如下所示:

     setTimeout(function() {
                deferred.resolve('foo');
                $rootScope.$apply();
            }, 2000);
    

    【讨论】:

    • 您应该使用 $timeout 而不是 setTimeout 和 $apply。这是同一件事,但更清洁和有角度的ar。所以应该是$timeout(function() { deferred.resolve('foo'); }, 2000);
    • 你说得对,我还指出了一个 $timeout 方法,它正在实现 $apply 本身,但我认为在他的示例中,setTimeout() 只是用来模仿 Promise 的异步性质.
    • 是的,你是对的 - 它是 :) 但是感谢 Andy 为其他关注此解决方案的人提出了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    相关资源
    最近更新 更多