而试图调用我得到这个错误
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'];
错误是
Error: $digest already in progress
复制: 调用$范围时,为防止错误$已经消化进度$适用()。
您获得的错误意味着角的脏检查正在进行中。
最近的最佳做法,说我们应该用$timeout
,如果我们想在未来消化迭代执行任何代码:
$timeout(function() {
// the code you want to run in the next digest
});
上一页反应:( 不要使用此方法 )
使用安全的应用,如:
$rootScope.$$phase || $rootScope.$apply();
你为什么不反转的条件?
$scope.$on('$locationChangeStart', function (event, next, current) {
if (confirm("Are you sure you want to leave this page?")) {
event.preventDefault();
}
});
对于其他人寻求解决此错误,这是值得注意的是, 文档似乎使用建议$timeout
服务,以确保代码将在一个被称为$apply
块。
$timeout(function() {
$scope.someData = someData;
});
在讨论这个问题,如果你看看过去接受的答案。
使用
$scope.evalAsync(function(){
});
代替
$scope.$apply(function(){
});
josliber的回答解决了我有一个类似$消化问题。 我只是用
$scope.$evalAsync(function(){
// code here
});
这里好文章https://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
因为你的$范围。$适用()是AngularJs环境 。一般里面我不会建议你使用$适用(),而且$ rootScope的。$适用()函数使您的应用程序运行slowly.It运行的新周期你的整个范围。