当用户离开页面时在 angularjs 中显示警报 [英] Showing alert in angularjs when user leaves a page

查看:29
本文介绍了当用户离开页面时在 angularjs 中显示警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angularjs 的新蜜蜂.我正在尝试编写一个验证,当他尝试关闭浏览器窗口时提醒用户.

I'm an angularjs new bee. I'm trying to write a validation which alerts the user when he tries to close the browser window.

我的页面 v1 和 v2 上有 2 个链接.点击链接后,它会转到特定页面.这是重定向到 v1 和 v2 的代码

I have 2 links on my page v1 and v2.When clicked on the links it takes to the specific pages. Here is the code to redirect to v1 and v2

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'])

.config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/v1', {templateUrl: 'pages/v_1.html', controller: MyCtrl1});
        $routeProvider.when('/v2', {templateUrl: 'pages/v_2.html', controller: MyCtrl2});
        $routeProvider.otherwise({redirectTo: '/v1'});
}]);

当用户点击 v1 时,我想弹出一条消息,如果他想继续的话,他将要离开 v1",点击 v2 时也是如此.任何有关如何实现这一目标的指示将不胜感激.

I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2. Any pointers on how to achieve this would be appreciated.

我得到了答案这里但它会在每个时间间隔后弹出消息.

I got an answer here but it pops up the message after every time interval.

更新代码;

控制器

function MyCtrl1() {
    $scope.$on('$locationChangeStart', function (event, next, current) {
        if ('your condition') {
            event.preventDefault();

            MessageService.showConfirmation(
                'Are you sure?',
            MessageService.MessageOptions.YES_NO, {
                'YES': function () {
                    blockNavigation = false;
                    $location.url($location.url(next).hash());
                    $rootScope.$apply();
                },
                'NO': function () {
                    MessageService.clear();
                    $log.log('NO Selected')
                }
            });
        }
    });
}
MyCtrl1.$inject = [];


function MyCtrl2() {}
MyCtrl2.$inject = [];

推荐答案

确认对话的代码可以这样写得更短:

The code for the confirmation dialogue can be written shorter this way:

$scope.$on('$locationChangeStart', function( event ) {
    var answer = confirm("Are you sure you want to leave this page?")
    if (!answer) {
        event.preventDefault();
    }
});

这篇关于当用户离开页面时在 angularjs 中显示警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆