页面离开前的Angularjs确认消息

Angularjs Confirmation Message before page leave

本文关键字:Angularjs 确认 消息 离开      更新时间:2023-09-26

我已经开始使用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方法采用这样的参数。

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

因此您可以使用超时值。我认为这应该行得通。

尝试在$rootScope而不是本地$scope上修改此事件的代码侦听。

例如:

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