【问题标题】:Angular: how to switch routes based on function callsAngular:如何根据函数调用切换路由
【发布时间】:2014-04-14 08:03:30
【问题描述】:

我的app.js 中有三个路由,但是当我从创建切换到任何其他路由时,我想检查用户是否有意点击切换或者是错误,所以会有返回弹出窗口询问用户留在页面上或离开页面。在通常情况下,它可以使用以下代码:

window.onbeforeunload = confirmExit;
function confirmExit() {
    return "You have attempted to leave this page. Are you sure?";
}

但由于这是一个 SPA 应用程序,我必须在切换路线时运行此功能:

这是我的路线

testApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/tests', {
        templateUrl: 'partials/list.html',
        controller: 'ListCtrl'
      }).
      when('/tests/:testsId', {
        templateUrl: 'partials/detail.html',
        controller: 'DetailCtrl'
      }).
      when('/create/', {
        templateUrl: 'partials/create.html',
        controller: 'CreateCtrl'
      }).
      otherwise({
        redirectTo: '/tests'
      });
  }]);

非常感谢任何帮助。

【问题讨论】:

    标签: angularjs routes onbeforeunload


    【解决方案1】:

    我会用一个角度指令来做到这一点:

    .directive('confirm', [
        function() {
            return {
                restrict: 'AEC',
                link: function($scope, element) {
                    element.bind('click', function(event) {
    
                            if (!confirm('You have attempted to leave this page. Are you sure?')) {
                                event.preventDefault();
                                return false;
                            }
                    });
                }
            };
        }
    ]);
    

    在您的 HTML 中:

    <a href="/route" confirm>link</a>
    

    这样标准的链接重定向将被拦截,并且只有在用户确认后才会发生重定向。

    工作小提琴:http://jsfiddle.net/HB7LU/3119/

    编辑: 移除 jquery 参考 + jsfiddle 链接

    edit2: 用于全局重定向拦截(如退格键或页面上的任何点击链接),请参阅此小提琴http://jsfiddle.net/9MnE9/124/

    在这里,我使用$routeChangeStart 来观察任何位置变化。

    【讨论】:

    • 如果有人按“BACKSPACE”怎么办??
    • 什么时候?重定向后?他将被重定向到上一页,就像任何其他 SPA/网站一样,但您可以选择不通过替换位置而不是添加新路线到位置历史记录(不是您问题的一部分)
    • 不,我在问,我在创建页面上,我按下了退格键,我可能来自其他页面,所以我将被重定向回该页面,在这种情况下,不会触发此指令。
    • 有什么办法我也可以在退格键上做到这一点吗??
    • 这仍然不适用于退格,如果我能以某种方式触发您在文档 keydown 事件退格上确认的指令,那么它可能会起作用。
    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2013-02-14
    • 1970-01-01
    • 2019-07-06
    • 2019-12-18
    • 1970-01-01
    相关资源
    最近更新 更多