角JS:链接的承诺和消化周期 [英] Angular JS: Chaining promises and the digest cycle

查看:102
本文介绍了角JS:链接的承诺和消化周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找到链的承诺来填充我的范围,然后有范围自动更新DOM。

I'm looking into chaining promises to populate my scope, and then having the scope automatically update the dom.

我运行到这个问题,但..如果我打电话,然后对已经解决的承诺,它会创建一个新的承诺(将调用成功函数异步但几乎立即)。我认为问题是,我们已经成功的函数被调用的时候留下的消化周期,所以DOM从未更新。

I'm running into problems with this though.. If I call "then" on an already resolved promise, it creates a new promise (that will call the success function asynchronously but almost immediately). I think the problem is that we've already left the digest cycle by the time the success function is called, so the dom never updates.

下面是code:

<div ng-controller="MyCtrl">
    Hello, {{name}}! <br/>
    {{name2}}<br/>
    <button ng-click="go()">Clickme</button><br/>
    {{name3}}
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, $q) {
    var data = $q.defer();    
    setTimeout(function() {$scope.$apply(data.resolve("Some Data"))}, 2000);
    var p = data.promise;

    $scope.name = p.then(angular.uppercase);
    $scope.name2 = p.then(function(x) { return "Hi "+x;});
    $scope.go = function() {
            $scope.name3 = p.then(function(x) { 
                // uncomment this to make it work:
                //$scope.$apply();
                return "Finally: "+x;
            });
    };
 }

http://jsfiddle.net/QZM4d/

是否有某种方式来完成这项工作,而无需调用$申请每次我许诺链时间?

Is there some way to make this work without calling $apply every time I chain promises?

推荐答案

报价 @ pkozlowski.opensource:

To quote @pkozlowski.opensource:

在AngularJS承诺拆分的结果异步传播,一个$消化周期内。因此,与当时()注册的回调将只在进入一个消化$名为周期

In AngularJS the results of promise resolution are propagated asynchronously, inside a $digest cycle. So, callbacks registered with then() will only be called upon entering a $digest cycle.

所以,当单击按钮时,我们正处在一个周期的消化。则()创建一个新的承诺,但该则()的结果将不会传播,直到的下次的消化周期,这还没有出现(因为没有$超时或$ HTTP或DOM事件触发一个)。如果添加与不执行任何NG-点击另一个按钮,然后单击,就会造成消化周期,你会看到的结果:

So, when the button is clicked, we are in a digest cycle. then() creates a new promise, but the results of that then() will not be propagated until the next digest cycle, which never comes (because there is no $timeout, or $http, or DOM event to trigger one). If you add another button with ng-click that does nothing, then click that, it will cause a digest cycle and you'll see the results:

<button ng-click="">Force digest by clicking me</button><br/>

下面是一个小提琴的做到这一点。

Here's a fiddle that does that.

小提琴也使用$来代替超时的setTimeout的 - 那么$适用()不需要

The fiddle also uses $timeout instead of setTimeout -- then $apply() isn't needed.

希望这是明确的,当你需要使用$适用。有时候,你需要手动调用它。

Hopefully it is clear when you need to use $apply. Sometimes you do need to call it manually.

这篇关于角JS:链接的承诺和消化周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆