AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

前端 未结 28 3106
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:31

I\'m finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call

28条回答
  •  野性不改
    2020-11-21 23:25

    Understanding that the Angular documents call checking the $$phase an anti-pattern, I tried to get $timeout and _.defer to work.

    The timeout and deferred methods create a flash of unparsed {{myVar}} content in the dom like a FOUT. For me this was not acceptable. It leaves me without much to be told dogmatically that something is a hack, and not have a suitable alternative.

    The only thing that works every time is:

    if(scope.$$phase !== '$digest'){ scope.$digest() }.

    I don't understand the danger of this method, or why it's described as a hack by people in the comments and the angular team. The command seems precise and easy to read:

    "Do the digest unless one is already happening"

    In CoffeeScript it's even prettier:

    scope.$digest() unless scope.$$phase is '$digest'

    What's the issue with this? Is there an alternative that won't create a FOUT? $safeApply looks fine but uses the $$phase inspection method, too.

提交回复
热议问题