gpt4 book ai didi

javascript - AngularJs - 确认对话框导致错误 "$digest already in progress"

转载 作者:行者123 更新时间:2023-11-28 05:47:27 25 4
gpt4 key购买 nike

按照答案here ,我有以下代码:

.directive('confirmOnExit', function($window) {
return {
scope: {},
link: function(scope) {
var message = "Changes you made may not be saved.";
$window.onbeforeunload = function(){
return message;
};
scope.$on('$locationChangeStart', function(event) {
if(!$window.confirm("Do you want to leave this page? "+message))
event.preventDefault();
});
scope.$on('$destroy',function(){
$window.onbeforeunload = null;
});
}
};
})

在 Chrome 上,一切都很好。但是,在 Firefox 上,几乎每次单击确认对话框的按钮时,都会出现错误:

错误:[$rootScope:inprog] $digest 已在进行中

我在网上找到的解决方案大多建议使用$timeout。但是,$timeout 函数内的 event.preventDefault() 似乎并不能阻止 URL 更改。我该怎么办?

最佳答案

我刚刚遇到了同样的问题。对我来说,调用confirm会导致firefox和IE中出现错误。为了解决这个问题,如果有消息要显示,我会立即阻止默认,并在超时后运行确认。然后,如果用户单击“离开页面”,我会清除 onbeforeunload 并使用 $location 服务再次设置 url。如果您的应用程序是单页应用程序,则 $locationChangeStart 将在第一个页面加载时被调用,因此您需要在顶部添加一个标志,例如: if (!hasLoaded) { hasLoaded = true;返回; }

$rootScope.$on('$locationChangeStart', function (e, newUrl, oldUrl) {
// Call the function and show the confirm dialogue if necessary
if ($window.onbeforeunload) {
let message = $window.onbeforeunload();

if (message) {
// Since we're going to show a message, cancel navigation
e.preventDefault();
$timeout(() => {
if (confirm(message)) {
// User chose not to stay. Unregister the function so that it doesn't fire again.
$window.onbeforeunload = undefined;

// Run the url again. We've cleared onbeforeunload, so this won't create a loop
$location.url(newUrl.replace($window.location.protocol + '//' + $window.location.host, ''));
}
});
}
}
})

关于javascript - AngularJs - 确认对话框导致错误 "$digest already in progress",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com