gpt4 book ai didi

javascript - 页面离开前的 Angularjs 确认消息

转载 作者:行者123 更新时间:2023-12-04 19:47:35 25 4
gpt4 key购买 nike

我已经开始使用 Angularjs 并创建了一个小型应用程序。在此应用程序中,我在页面上向用户展示了一个表单。我想在离开页面或刷新页面之前向用户显示确认消息。为此,我正在使用以下代码-

$scope.$on('$locationChangeStart', function(event, next, current) {    
if(!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
});

当我使用这段代码时,它工作正常,但它在控制台面板中抛出错误。错误是“错误:$digest 已经在进行中”。

当我搜索此问题的解决方案时,发现了一些使用 $timeout 的建议。所以,我在我的代码中使用了它,如下所示-

$scope.$on('$locationChangeStart', function(event, next, current) {    
$timeout( function() {
if(!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
});
});

当我使用 $timeout 时,错误消失但页面在确认消息之前离开。

有人知道吗?

最佳答案

你可以使用

$timeout(fn{}, delay);

来自 angular js 文档,超时方法采用这样的参数。

$timeout([fn], [delay], [invokeApply], [Pass]);

因此您可以使用超时值。我认为这应该有效。

关于javascript - 页面离开前的 Angularjs 确认消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34171476/

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