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

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

本文关键字:浏览器 显示 按钮 数据 指令 js 表单 保存 Angular      更新时间:2023-09-26

我是angularjs的新手。当表单有未保存的数据并且用户按下浏览器返回按钮时,是否有任何方法显示警报。任何关于如何实现这一目标的建议都将不胜感激。

更新::

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

更新的代码

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

是的,我几分钟前刚刚给另一个用户给出了这个答案,在根作用域级别创建一个手表来捕捉位置变化:

$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);

正如您所发现的,您可以编写一个自定义指令来监视更改。您的更新代码已步入正轨,但您可以做一些改进:

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

  2. 确实没有必要观察$location.path(),因为绑定到$locationChangeStart也会做同样的事情。

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

希望您能发现该指令内容丰富。请随意从中学习,甚至在项目中使用它。