angularjs ng-show with promise expression

后端 未结 3 862
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 11:50

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.

相关标签:
3条回答
  • 2021-01-17 12:24

    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)
    
    0 讨论(0)
  • 2021-01-17 12:29

    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>
    
    0 讨论(0)
  • 2021-01-17 12:31

    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 讨论(0)
提交回复
热议问题