Why is using if(!$scope.$$phase) $scope.$apply() an anti-pattern?

后端 未结 6 835
生来不讨喜
生来不讨喜 2020-11-28 02:24

Sometimes I need to use $scope.$apply in my code and sometimes it throws a \"digest already in progress\" error. So I started to find a way around this and foun

6条回答
  •  隐瞒了意图╮
    2020-11-28 02:49

    In any case when your digest in progress and you push another service to digest, it simply gives an error i.e. digest already in progress. so to cure this you have two option. you can check for anyother digest in progress like polling.

    First one

    if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
        $scope.$apply();
    }
    

    if the above condition is true, then you can apply your $scope.$apply otherwies not and

    second solution is use $timeout

    $timeout(function() {
      //...
    })
    

    it will not let the other digest to start untill $timeout complete it's execution.

提交回复
热议问题