根据AngularJS(1.3.15)的来源,FormController的方法$setPristine()
将表单$submitted
状态重置为false:
form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};
问题在于,在提交并calling this method inside a controller后,表单会恢复为$submitted = false
。是预期还是错误?
答案 0 :(得分:9)
您看到此行为的原因是重置按钮没有type =" button"或者输入="重置"属性,因此默认情况下它表现为提交按钮。因此,将表单设置为pristine的ng-click实际上将$ submit设置为false,但之后立即再次提交表单。
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
this.data = {
name: ''
};
this.reset = function(form) {
this.data.name = '';
form.$setPristine();
};
});
HTML页面:
<html ng-app="plunker">
<head>
<title>form.$submitted</title>
<script src="http://code.angularjs.org/1.3.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl">
<form name="form" novalidate>
<input name="name" ng-model="ctrl.data.name" placeholder="Name" required />
<input type="submit" />
<button type="button" class="button" ng-click="ctrl.reset(form)">Reset</button>
</form>
<pre>
Pristine: {{form.$pristine}}
Submitted: {{form.$submitted}}
</pre>
</div>
http://plnkr.co/edit/kRxEVu?p=preview
希望这是你想要的那个
来源:https://github.com/angular/angular.js/issues/10006#issuecomment-62640975
答案 1 :(得分:2)
您可以在提交后通过添加$ setUntouched()&amp;重置表单。 $ setPristine()在提交表单后表单名称或者在您的Ajax请求成功时。例如: -
<form name="userDetailsForm"
ng-submit="addUserDetails(userDetailsForm.$valid)"
novalidate>
<div class="field name-field">
<input class="input" type="text" name="name" ng-model="form.data.name" required placeholder="First Name + Last Name" />
<div ng-if="userDetailsForm.$submitted || userDetailsForm.name.$touched" ng-messages="signupForm.name.$error">
<div ng-message="required">You did not enter your name</div>
</div>
</div>
<input type="submit" value="Add Details" class="btn btn-default" />
</form>
$scope.addUserDetails = function(valid) {
if(!valid) return;
//Your Ajax Request
$scope.userDetailsForm.$setUntouched();
$scope.userDetailsForm.$setPristine();
};