检测未保存的更改并使用angularjs提醒用户

检测未保存的更改并使用angularjs提醒用户,第1张

检测未保存的更改并使用angularjs提醒用户

这样的事情应该做到:

<!doctype html><html ng-app="myApp"><head>    <script src="http://pre.angularjs.org/1.1.2/angular.min.js"></script>    <script type="text/javascript">    function Ctrl($scope) {        var initial = {text: 'initial value'};        $scope.myModel = angular.copy(initial);        $scope.revert = function() { $scope.myModel = angular.copy(initial); $scope.myForm.$setPristine();        }    }    angular.module("myApp", []).directive('/confirm/iOnExit', function() {        return { link: function($scope, elem, attrs) {     window.onbeforeunload = function(){         if ($scope.myForm.$dirty) {  return "The form is dirty, do you want to stay on the page?";         }     }     $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();  }         }     }); }        };    });    </script></head><body>    <form name="myForm" ng-controller="Ctrl" /confirm/i-on-exit>        myModel.text: <input name="input" ng-model="myModel.text">        <p>myModel.text = {{myModel.text}}</p>        <p>$pristine = {{myForm.$pristine}}</p>        <p>$dirty = {{myForm.$dirty}}</p>        <button ng-click="revert()">Set pristine</button>    </form></body></html>

请注意,在此示例中未触发$
locationChangeStart的侦听器,因为在这样一个简单的示例中AngularJS不处理任何路由,但它应在实际的Angular应用程序中运行。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5639132.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存