Showing alert in angularjs when user leaves a page

后端 未结 6 647
借酒劲吻你
借酒劲吻你 2020-11-28 22:04

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.

I have 2 links on my page v1 and v2.Whe

6条回答
  •  误落风尘
    2020-11-28 22:35

    Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.

    .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();
                    }
                });
            }
        };
    }]);
    

提交回复
热议问题