[英]Angularjs Confirmation Message before page leave
I have started with Angularjs and creating a small application. 我已经开始使用Angularjs并创建一个小应用程序。 In this application I am showing a form to user on a page.
在这个应用程序中,我在页面上向用户显示一个表单。 I want to show confirmation message to user before leaving a page or refreshing the page.
我想在离开页面或刷新页面之前向用户显示确认消息。 I am using the below code for this purpose-
我为此目的使用以下代码 -
$scope.$on('$locationChangeStart', function(event, next, current) {
if(!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
});
When I used this code then it is working fine but it throws an error in console panel. 当我使用这个代码然后它工作正常但它在控制台面板中引发错误。 Error is "Error: $digest already in progress".
错误是“错误:$ digest已在进行中”。
When I search solution for this issue then found some suggestion to use $timeout. 当我搜索此问题的解决方案时,然后找到一些建议使用$ timeout。 So, I used it in my code as like below-
所以,我在我的代码中使用它,如下所示 -
$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();
}
});
});
When I used $timeout then error gets disappear but page gets leave before confirmation message. 当我使用$ timeout时,错误消失,但页面在确认消息之前离开。
Does any one has some idea about it ? 有没有人对此有所了解?
you may use 你可以用
$timeout(fn{}, delay);
from angular js documentation the timeout method takes the argument like this. 从angular js文档中,timeout方法接受这样的参数。
$timeout([fn], [delay], [invokeApply], [Pass]);
so you can use a timeout value. 所以你可以使用超时值。 i think this should work.
我认为这应该有效。
Try modifying your code listen for this event on the $rootScope, not the local $scope. 尝试修改代码在$ rootScope上侦听此事件,而不是本地$ scope。
Ex: 例如:
$rootScope.$on('$locationChangeStart', function(event, next, current) {
if(!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.