[英]Using $dirty in angularjs in order to check whenever a form is being edited
I was trying to check whenever my form is being edited by writing some fields of it. 我试图通过写一些字段来检查我的表单是否正在编辑。 I read $dirty should work for that task but I can't figure out what I'm missing here: 我读过$ dirty应该为这个任务工作,但我无法弄清楚我在这里缺少什么:
<!DOCTYPE html>
<html lang="en">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form name = "myForm" novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p> is Form dirty? {{isDirty}}<p>
<p>form = {{user }}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName:"John", lastName:"Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
$scope.isDirty = $scope.myForm.$dirty;
});
</script>
</body>
</html>
I'm trying to make the flag isDirty to true whenever the user modifies the form. 我试图在用户修改表单时将标志isDirty设为true。 Thanks 谢谢
You are missing name
attributes in your form fields which are not enabling form validation for those field. 您缺少表单字段中的name
属性,这些属性未启用这些字段的表单验证。 You need to add unique name for each field so that it will get add those field in myForm
object 您需要为每个字段添加唯一名称,以便在myForm
对象中添加这些字段
Markup 标记
<form name="myForm" novalidate>
First Name:<br>
<input type="text" name="firstName" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" name="lastName" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
Also you are accessing myForm
object which is nothing but form object, I won't be available until DOM get rendered, $scope.myForm
will be simply undefined at the time of controller initilization, If you really want to access $scope.myForm
from controller then you need to put that code in $timeout
that will run $timeout
function code in next digest cycle. 你也正在访问myForm
对象,它只是表单对象,在DOM被渲染之前我将无法使用, $scope.myForm
在控制器$scope.myForm
将简单地未定义,如果你真的想从$scope.myForm
访问控制器然后你需要将该代码放在$timeout
,这将在下一个摘要周期中运行$timeout
功能代码。
$timeout(function(){
$scope.isDirty = $scope.myForm.$dirty;
});
Update 更新
There is no need to maintain a separate isDirty
flag (this would require to change the separate isDirty
flag to reflect any changes in myForm.$dirty
flag.) Instead I suggest you use $scope.myForm.$dirty
directly as a flag. 没有必要维护一个单独的 isDirty
标志(这将需要更改单独的isDirty
标志以反映myForm.$dirty
标志中的任何更改。)相反,我建议您直接使用$scope.myForm.$dirty
作为标志。 So use the expression myForm.$dirty
, and this flag will change as form gets dirty. 所以使用表达式myForm.$dirty
,这个标志会随着表单变脏而改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.