【问题标题】:Angularjs Confirmation Message before page leave页面离开前的Angularjs确认消息
【发布时间】:2015-12-09 05:38:24
【问题描述】:

我已经开始使用 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 时,错误会消失,但页面会在确认消息之前离开。

有人知道吗?

【问题讨论】:

  • 请创建一个小提琴。我没有收到 $digest 错误消息。

标签: javascript angularjs


【解决方案1】:

你可以使用

$timeout(fn{}, delay);

从角度 js 文档中,超时方法采用这样的参数。

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

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

【讨论】:

    【解决方案2】:

    尝试修改您的代码在 $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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2013-01-28
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      相关资源
      最近更新 更多