【问题标题】:Angularjs handling leaving a template in various ways?Angularjs以各种方式处理离开模板?
【发布时间】:2015-07-23 16:30:44
【问题描述】:

我正在尝试在我的 Angular 模块中实现一个函数,该函数将触发一个事件来保存页面上的更改。用户离开页面的不同方式是:

  1. 单击加载新模板的链接。
  2. 单击返回按钮
  3. 关闭选项卡/窗口

我的实现使用以下代码处理 #1:

.directive('confirmOnExit', function() {
    return {
        link: function($scope, elem, attrs) {
            window.onbeforeunload = function(){
                    return "If you leave this page, you will exit the practice session. You will be able to view your score report for the completed session but will have to start a new one if you want to continue practicing.";
            }
            $scope.$on('$locationChangeStart', function(event, next, current) {
                    if($scope.$dirty & confirm("Are you sure you want to leave this practice session?")) {
                        console.log("Will end session!");
                        end_session();
                    }
            });
        }
    };
});

但是,当 #2 或 #3 出现时,会显示弹出对话框,但似乎没有触发 end_session() 函数。

任何关于如何处理后退按钮和关闭选项卡/窗口的见解将不胜感激?

【问题讨论】:

    标签: javascript angularjs django


    【解决方案1】:

    对我来说听起来像是一种竞争条件。 end_session() 可能不会在浏览器成功卸载页面之前触发,但如果没有更多代码,我真的无能为力,因为我不确定 end_session() 的作用。

    可以做的是捕获 locationChangeStart 并将其推迟到所有卸载任务完成后。

    快速说明,直接引用窗口是一种 Angular 的“反模式”: https://docs.angularjs.org/api/ng/service/$window

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2011-02-26
      • 2019-12-15
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多