小编典典

用户离开页面时在angularjs中显示警报

angularjs

我是angularjs新蜜蜂。我正在尝试编写一个验证,当用户尝试关闭浏览器窗口时会发出警告。

我的页面v1和v2上有2个链接。单击链接时,它指向特定页面。这是重定向到v1和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时也是如此。任何有关如何实现这一目标的指针将不胜感激。

我在这里得到了答案,但是在每个时间间隔后都会弹出该消息。

更新的代码;

控制器

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 = [];

阅读 330

收藏
2020-07-04

共1个答案

小编典典

确认对话框的代码可以这样写:

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