I want to reset form and all validation messages after submitting a form. Here is plunker:
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:
<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.
Is it possible to do in AngularJS? Thanks!
I want to reset form and all validation messages after submitting a form. Here is 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:
<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.
Is it possible to do in AngularJS? Thanks!
Share Improve this question asked Oct 6, 2015 at 15:17 Anna MiroshnichenkoAnna Miroshnichenko 1,2131 gold badge9 silver badges25 bronze badges 1- Duplicate of stackoverflow./questions/26015010/angularjs-form-reset-error – DexTer Commented Oct 6, 2015 at 15:41
1 Answer
Reset to default 5I'm surrpised but $setpristine()
doesn't update $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;
});
}
});
DEMO