
这样的事情应该做到:
<!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应用程序中运行。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)