使用angularjs检测未保存的数据 [英] Detect unsaved data using angularjs
问题描述
我是 AngularJs 的新手,所以这可能是微不足道的.是否有任何内置的 AngularJs directive
来检测表单中未保存的数据.如果没有,那么如何去写一个.任何指针将不胜感激.
I'm a newbie to AngularJs, so this might be trivial.
Are there any inbuilt AngularJs directive
to detect unsaved data in a form.
If not then how to go about writing one.
Any pointers would be appreciated.
html 代码是
<input type="text" runat="server" />
我的 Angular js 控制器代码是
And my angular js controller code is
function MyCtrl1($scope) {
// code to do stuff
}MyCtrl1.$inject = ['$scope'];
我正在尝试编写一个指令来检测未保存的数据,我猜它应该写在上面的控制器中.如果有错,请纠正我.
I am trying to write a directive to detect unsaved data, and I'm guessing its to be written in the above controller.Correct me if wrong.
推荐答案
AngularJS 在任何输入字段上设置 CSS 类 ng-pristine
和 ng-dirty
使用 ng-model,并且您的 FormController 具有属性 $pristine
和 $dirty
,您可以检查表单是否脏.所以是的,这是可能的.
AngularJS sets the CSS classes ng-pristine
and ng-dirty
on any input field you've used ng-model on, and your FormController has the properties $pristine
and $dirty
which you can check to see if the form is dirty or not. So yes, it's possible.
您能否提供一些代码来显示您正在尝试做什么?这样可以更轻松地为您提供帮助.
Could you provide some code that shows what you're trying to do? That would make it easier to help you.
编辑
以下是如何检测原始/脏状态以及如何恢复原始状态的简单示例:
Here's a simple example of how to detect a pristine/dirty state, and how to revert to a pristine state:
<!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>
这篇关于使用angularjs检测未保存的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!