javascript 提交表单后如何重置表单和验证(AngularJS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32973606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How reset form and validation after submitting form (AngularJS)
提问by Telary
I want to reset form and all validation messages after submitting a form. Here is plunker:http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview
我想在提交表单后重置表单和所有验证消息。这是plunker:http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ? p=preview
My code is bellow:
我的代码如下:
Controller:
控制器:
app.controller('MainCtrl', function($scope) {
$scope.data={fullName:''};
$scope.submit=function(){
console.log('submit')
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.data={fullName:''};
}
});
HTML:
HTML:
<body ng-controller="MainCtrl">
<form name="myForm" novalidate>
<div>
<label class="control-label">Name</label>
<input
name="full_name"
type="text"
ng-model="data.fullName"
ng-required="true">
<p ng-if="myForm.$submitted && myForm.$invalid">Validation message</p>
</div>
<button ng-click="submit()" type="submit">
Submit
</button>
</form>
</body>
My problem is: when user enters name in the input and clicks on Submit button, validation message shouldn't be shown, because model, form and validation should be resetted. How I can do it?
我的问题是:当用户在输入中输入名称并点击提交按钮时,不应显示验证消息,因为模型、表单和验证应该被重置。我该怎么做?
I tried to use $setPristine() and $setUntouched(), but it doesn't work for me.
我尝试使用 $setPristine() 和 $setUntouched(),但它对我不起作用。
Is it possible to do in AngularJS? Thanks!
可以在 AngularJS 中做吗?谢谢!
回答by charlietfl
I'm surrpised but $setpristine()
doesn't update $submitted
.
我很惊讶,但$setpristine()
没有更新$submitted
。
This may not be the prettiest solution but seems to work:
这可能不是最漂亮的解决方案,但似乎有效:
app.controller('MainCtrl', function($scope, $timeout) {
$scope.data = {
fullName: ''
};
$scope.submit = function() {
console.log('submit')
$scope.data = {
fullName: ''
};
$timeout(function() {
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.myForm.$submitted = false;
});
}
});