错误:$ digest已在进行中

iJa*_*ade 29 javascript angularjs angularjs-directive

我试图打电话时遇到这个错误

        function MyCtrl1($scope, $location, $rootScope) {
      $scope.$on('$locationChangeStart', function (event, next, current) {
        event.preventDefault();
        var answer = confirm("Are you sure you want to leave this page?");
        if (answer) {
          $location.url($location.url(next).hash());
          $rootScope.$apply();
        }
      });
    }

MyCtrl1.$inject = ['$scope', '$location', '$rootScope'];
Run Code Online (Sandbox Code Playgroud)

错误是

Error: $digest already in progress
Run Code Online (Sandbox Code Playgroud)

bml*_*ite 61

重复:在调用$ scope时防止错误$ digest正在进行中.$ apply()

你得到的错误意味着Angular的脏检查已经在进行中.

最近的最佳实践表明,$timeout如果我们想在下一个摘要迭代中执行任何代码,我们应该使用它们:

$timeout(function() {
  // the code you want to run in the next digest
});
Run Code Online (Sandbox Code Playgroud)

上一页反应:(不要使用此方法)

使用安全申请,如下所示:

$rootScope.$$phase || $rootScope.$apply();
Run Code Online (Sandbox Code Playgroud)

你为什么不改变这种情况?

$scope.$on('$locationChangeStart', function (event, next, current) {                
    if (confirm("Are you sure you want to leave this page?")) {
        event.preventDefault();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 更新了我的整个代码...它现在没有显示错误,但它没有达到目的,转到下一个视图 (3认同)
  • 根据该项目,您不应该使用$$阶段,因为它将来会消失,并会破坏您的代码.http://github.com/angular/angular.js/wiki/Anti-Patterns相反,只需在$ timeout内包装您认为需要安全应用的任何内容.它将在当前的摘要周期后安全应用. (2认同)

aw0*_*w04 12

对于其他希望解决此错误的人来说,值得注意的是,文档似乎建议使用该$timeout服务来确保在单个$apply块中调用代码.

$timeout(function() {
  $scope.someData = someData;
});
Run Code Online (Sandbox Code Playgroud)

如果您查看已接受的答案,也会在此问题中进行讨论.