使用 angularjs 检测未保存的更改并提醒用户 [英] Detect unsaved changes and alert user using angularjs
本文介绍了使用 angularjs 检测未保存的更改并提醒用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是目前的代码
<!doctype html>
<html ng-app>
<head>
<script src="http://code.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();
}
}
</script>
</head>
<body>
<form name="myForm" ng-controller="Ctrl">
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>
如果有一些未保存的数据,如何在浏览器关闭
或url重定向
时发出警报,以便用户决定是否继续?
How to alert on browser close
or url redirect
in case there is some unsaved data, so that user can decide whether to continue?
推荐答案
应该这样做:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.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('confirmOnExit', 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-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 应用程序中工作.
Note that the listener for $locationChangeStart isn't triggered in this example since AngularJS doesn't handle any routing in such a simple example, but it should work in an actual Angular application.
这篇关于使用 angularjs 检测未保存的更改并提醒用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文