javascript Angular js 指令在表单中未保存数据时显示浏览器后退按钮的警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14893867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:51:26  来源:igfitidea点击:

Angular js directive to show alert for browser back button when unsaved data in form

javascriptangularjsangularjs-directive

提问by iJade

I'm a newbie to angularjs.Is there any way to show alert when a form has unsaved data and user presses browser back button. Any pointers to how to achieve this would be appreciated.

我是 angularjs 的新手。当表单有未保存的数据并且用户按下浏览器后退按钮时,有什么方法可以显示警报。任何有关如何实现这一目标的指针将不胜感激。

Update: :

更新: :

    angular.module('myApp.directives', []).directive('confirmOnExit', function() {
    return {
        link: function($scope, elem, attrs) {


            $scope.$on('$locationChangeStart', function(event, next, current) {

                if ($scope.myForm.$dirty) {
                    if(!confirm("Ahh the form is dirty, do u want to continue?")) {
                        event.preventDefault();
                    }
                }
            });

            window.onbeforeunload = function(){
                alert('me');
                if ($scope.myForm.$dirty) {
                    return "The Form is Dirty.";
                }
            }
        }
    };
});

Updated code

更新代码

    angular.module('myApp.directives', []).directive('confirmOnExit', function () {
    return {
        link: function ($scope, elem, attrs, $rootScope) {
            window.onbeforeunload = function () {
                if ($scope.myForm.$dirty) {
                    return " do you want to stay on the page?";
                }
            }

            $rootScope.$watch(function {
                return $location.path();
            },

            function (newValue, oldValue) {
                if (newValue != oldvalue) {
                    // here you can do your tasks
                } else {}
            },
            true);

            $scope.$on('$locationChangeStart', function (event, next, current) {
                if ($scope.myForm.$dirty) {
                    if (!confirm("The form is dirty, do you want to stay on the page?")) {
                        event.preventDefault();
                    }
                }
            });
        }
    };
});

回答by remigio

Yes, I just gave this answersome minutes ago to another user, create a watch at root scope level to catch location changing:

是的,几分钟前我刚刚将这个答案提供给另一个用户,在根范围级别创建一个监视以捕获位置更改:

$rootScope.$watch(function() { // fixed function declaration
   return $location.path();
   },  
   function(newValue, oldValue) {  
      if (newValue != oldValue) { // Update: variable name case should be the same
         // here you can do your tasks
      }
      else {
      }
   },
   true);

回答by facultymatt

As you've discovered, you can write a custom directive to watch for changes. Your updated code is on track, however there are a few things you could do to improve:

正如您所发现的,您可以编写一个自定义指令来监视更改。您更新的代码正在按计划进行,但是您可以做一些事情来改进:

  1. Your directive references the form by name, which limits it's re-usability. For example, what if you wanted to use this same directive on a form called myOtherForm? Currently using $scope.myForm.$dirtylimits this flexibility. Instead, a better approach is to bind to the formController in your linking function.

  2. There really isn't a need to watch $location.path()since binding to $locationChangeStartwill do the same thing.

  1. 您的指令按名称引用表单,这限制了它的可重用性。例如,如果您想在名为myOtherForm? 当前使用$scope.myForm.$dirty限制了这种灵活性。相反,更好的方法是绑定到链接函数中的 formController。

  2. 真的没有必要看,$location.path()因为绑定到$locationChangeStart会做同样的事情。

I've written an angularjs directive that you can uses the approaches I've discussed above. @see https://github.com/facultymatt/angular-unsavedChanges

我写了一个 angularjs 指令,你可以使用我上面讨论的方法。@see https://github.com/facultymatt/angular-unsavedChanges

Hopefully you find this directive informative. Feel free to learn from it or even use it in your project.

希望您发现此指令信息丰富。随意从中学习,甚至在您的项目中使用它。