Angular js 指令在表单中未保存数据时显示浏览器后退按钮的警报 [英] Angular js directive to show alert for browser back button when unsaved data in form

查看:30
本文介绍了Angular js 指令在表单中未保存数据时显示浏览器后退按钮的警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

更新:

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

推荐答案

是的,我刚刚给了这个 几分钟前回答另一个用户,在根范围级别创建一个观察以捕捉位置变化:

Yes, I just gave this answer some 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);

这篇关于Angular js 指令在表单中未保存数据时显示浏览器后退按钮的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆