Getting AngularJS Error: “[$rootScope:inprog] $digest already in progress” without a manual $apply

风格不统一 提交于 2019-12-05 01:25:25

Add this little method and call it inplace of apply()

function CheckScopeBeforeApply() {
    if(!$scope.$$phase) {
         $scope.$apply();
    }
};

This solve the issue for me. Just add it one time, it you don't need to change you code any more:

https://github.com/angular/angular.js/issues/10083#issuecomment-145967719

.config(function($provide) {
  // Workaround for https://github.com/angular/angular.js/issues/10083
  $provide.decorator('$rootScope', ['$delegate', '$exceptionHandler',
    function($delegate, $exceptionHandler) {
      var proto = Object.getPrototypeOf($delegate);
      var originalDigest = proto.$digest, originalApply = proto.$apply;
      proto.$digest = function() {
        if ($delegate.$$phase === '$digest' || $delegate.$$phase === '$apply') return;
        originalDigest.call(this);
      };
      proto.$apply = function(fn) {
        if ($delegate.$$phase === '$digest' || $delegate.$$phase === '$apply') {
          try {
            this.$eval(fn);
          } catch(e) {
            $exceptionHandler(e);
          }
        } else {
          originalApply.call(this, fn);
        }
      };
      return $delegate;
    }
  ]);
})

I used alternate solution by putting $scope.$apply() in timeout like this and it worked...

setTimeout(function(){
  $scope.$apply();
},1);

I think it is just because, angular's apply lifecycle was already running and my manual $apply has interrupted it.

There's an easier solution:

$scope.$evalAsync(function() {
    // Code here
});

Or simply:

$scope.$evalAsync();

This avoids the problems caused by $scope.$apply(), though it should be noted that it won't run immediately (that's part of the reason you won't get the inprog error). I use this instead of $scope.$apply() and it has saved me from so much trouble.

See: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$evalAsync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!