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

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

    I have been able to solve this problem by calling $eval instead of $apply in places where I know that the $digest function will be running.

    According to the docs, $apply basically does this:

    function $apply(expr) {
      try {
        return $eval(expr);
      } catch (e) {
        $exceptionHandler(e);
      } finally {
        $root.$digest();
      }
    }
    

    In my case, an ng-click changes a variable within a scope, and a $watch on that variable changes other variables which have to be $applied. This last step causes the error "digest already in progress".

    By replacing $apply with $eval inside the watch expression the scope variables get updated as expected.

    Therefore, it appears that if digest is going to be running anyways because of some other change within Angular, $eval'ing is all you need to do.

提交回复
热议问题