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

前端 未结 28 3099
伪装坚强ぢ
伪装坚强ぢ 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:26

    Don't use this pattern - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't.

    You can check if a $digest is already in progress by checking $scope.$$phase.

    if(!$scope.$$phase) {
      //$digest or $apply
    }
    

    $scope.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and its children, and $apply will process the watchers of all scopes.

    To @dnc253's point, if you find yourself calling $digest or $apply frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a $digest is in progress, sometimes not. That's why I use this check.

    I would love to know a better way if anyone knows one.


    From comments: by @anddoutoi

    angular.js Anti Patterns

    1. Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.

提交回复
热议问题