最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs ng-show with promise expression - Stack Overflow

programmeradmin3浏览0评论

I'm using ng-show with an expression that resolves to a promise that resolves to a boolean. When I do this I get the 10 digest iterations overflow.

See

  <body ng-controller="MainCtrl">
    <p ng-show="returnsABoolean()">non promise</p>
    <p ng-show="returnsAPromiseThatResolvesToABoolean()">promise</p>
  </body>

Ctrl:

  $scope.returnsABoolean = ()->
    true

  $scope.returnsAPromiseThatResolvesToABoolean = ()->
    $q.when(false)

I know that {{somePromise}} will resolve, but {{returnsAPromiseThatResolvesToABoolean()}} seems to cause the same issue.

Any ideas? I'd expect this to work..

I'm using ng-show with an expression that resolves to a promise that resolves to a boolean. When I do this I get the 10 digest iterations overflow.

See http://plnkr.co/edit/XibYM0kCnXhKjNUeTsp3?p=preview

  <body ng-controller="MainCtrl">
    <p ng-show="returnsABoolean()">non promise</p>
    <p ng-show="returnsAPromiseThatResolvesToABoolean()">promise</p>
  </body>

Ctrl:

  $scope.returnsABoolean = ()->
    true

  $scope.returnsAPromiseThatResolvesToABoolean = ()->
    $q.when(false)

I know that {{somePromise}} will resolve, but {{returnsAPromiseThatResolvesToABoolean()}} seems to cause the same issue.

Any ideas? I'd expect this to work..

Share Improve this question asked Sep 6, 2013 at 21:19 Roy TrueloveRoy Truelove 22.5k21 gold badges115 silver badges154 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 7

AngularJS resolves the promise for template binding automatically. However, you should use the promise in ng-init to prevent the digest cycle from returning a new promise every tick.

<p ng-init="v=returnsAPromiseThatResolvesToABoolean()" ng-show="v">promise</p>

Plunker: http://plnkr.co/edit/NvjP5qHafhyIWXXotBej?p=preview

This works as I think you intended it to. $q.when() returns a promise object, so ng-show is not getting a boolean value; it's getting a promise object.

Updated template:

  <body ng-controller="MainCtrl">
    <p ng-show="returnsABoolean()">non promise</p>
    <p ng-show="returnsAPromiseThatResolvesToABoolean">promise</p>
  </body>

Updated Ctrl:

  $scope.returnsABoolean = ()->
    true

  promise = $q.when(false)
  promise.then((val) ->
    $scope.returnsAPromiseThatResolvesToABoolean = val)

If you check out the sources here you 'll see that the promise is resolved in nextTick, so the $scope only changes the next time angular makes a $digest cycle. But your function returns a new promise on every $digest cycle, never actually getting the resolved value of the previous promise.

It's an old problem discussed here also.

You can overcome this issue by keeping a "persistent" reference to your promise outside the function as I did here.

发布评论

评论列表(0)

  1. 暂无评论