Programing

사용자가 페이지를 떠날 때 angularjs에 경고 표시

lottogame 2020. 12. 10. 08:23
반응형

사용자가 페이지를 떠날 때 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 = [];

확인 대화 상자의 코드는 다음과 같이 더 짧게 작성할 수 있습니다.

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

두 가지 다른 질문에 대해 질문을 분리 해 보겠습니다.

1.

사용자가 브라우저 창을 닫으려고 할 때 경고하는 유효성 검사를 작성하려고합니다.

2.

사용자가 v1을 클릭 할 때 "계속하려면 v1에서 나 가려고합니다"라는 메시지를 표시하고 v2를 클릭 할 때도 동일합니다.

첫 번째 질문의 경우 다음과 같이하십시오.

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}

두 번째 질문의 경우 다음과 같이하십시오.

$locationChangeStart전환 이벤트를보기 위해 연결 하려면 이벤트를 처리해야하므로이 코드를 사용하여 컨트롤러에서 전환 유효성 검사를 처리합니다.

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

내가 사용하는 지시문은 다음과 같습니다. 양식이 언로드되면 자동으로 정리됩니다. 프롬프트가 실행되지 않도록하려면 (예 : 양식을 성공적으로 저장했기 때문에) $ scope.FORMNAME. $ setPristine ()을 호출하십시오. 여기서 FORMNAME은 프롬프트하지 않으려는 양식의 이름입니다.

.directive('dirtyTracking', [function () {
    return {
        restrict: 'A',
        link: function ($scope, $element, $attrs) {
            function isDirty() {
                var formObj = $scope[$element.attr('name')];
                return formObj && formObj.$pristine === false;
            }

            function areYouSurePrompt() {
                if (isDirty()) {
                    return 'You have unsaved changes. Are you sure you want to leave this page?';
                }
            }

            window.addEventListener('beforeunload', areYouSurePrompt);

            $element.bind("$destroy", function () {
                window.removeEventListener('beforeunload', areYouSurePrompt);
            });

            $scope.$on('$locationChangeStart', function (event) {
                var prompt = areYouSurePrompt();
                if (!event.defaultPrevented && prompt && !confirm(prompt)) {
                    event.preventDefault();
                }
            });
        }
    };
}]);

As you've discovered above, you can use a combination of window.onbeforeunload and $locationChangeStart to message the user. In addition, you can utilize ngForm.$dirty to only message the user when they have made changes.

I've written an angularjs directive that you can apply to any form that will automatically watch for changes and message the user if they reload the page or navigate away. @see https://github.com/facultymatt/angular-unsavedChanges

Hopefully you find this directive useful!


The other examples here work fine for the old versions of ui-router (>=0.3.x) but all state events, such as $stateChangeStart, are deprecated as of 1.0. The new ui-router 1.0 code uses the $transitions service. So you need to inject $transitions into your component then use the $transitions.onBefore method as the code below demonstrates.

$transitions.onBefore({}, function(transition) {
  return confirm("Are you sure you want to leave this page?");
});

This is just a super simple example. The $transitions service can accept more complicated responses such as promises. See the HookResult type for more information.


$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

$scope.init = function () {
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        };

Reload page: using init

참고URL : https://stackoverflow.com/questions/14809686/showing-alert-in-angularjs-when-user-leaves-a-page

반응형