I'm using an AngularJS form for a contact form and would like to reset the form on successful submission. I've found plenty of examples of how to reset an AngularJS Form and have that working, however, I've been unable to figure out a way to successfully reset the form on submission. My reset() function clears the form fields and appears to set the state of the form back to pristine when called on submit, however, the messages that should only be shown when a field is invalid are still displayed.
Here's my controller code with the function...
function ContactCtrl() {
var vm = this;
vm.reset = reset;
vm.submit = submit;
function reset(form) {
if (form) {
vm.name = undefined;
vm.email = undefined;
form.$setValidity();
form.$setPristine();
form.$setUntouched();
}
}
function submit(form) {
if (form) {
vm.reset(form);
}
}
}
The full code can be found below or on Plunker
angular
.module('plunker', [])
.controller('ContactCtrl', ContactCtrl);
function ContactCtrl() {
var vm = this;
vm.reset = reset;
vm.submit = submit;
function reset(form) {
if (form) {
vm.name = undefined;
vm.email = undefined;
form.$setValidity();
form.$setPristine();
form.$setUntouched();
}
}
function submit(form) {
if (form) {
vm.reset(form);
}
}
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ContactCtrl as contact">
<form name="form" novalidate>
Name:
<input type="text" ng-model="contact.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="contact.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
<input type="button" ng-click="contact.reset(form)" value="Reset" />
<input type="submit" ng-click="contact.submit(form)" value="Submit" />
</form>
<pre>
FORM:
form.$pristine = {{form.$pristine}}
form.$dirty = {{form.$dirty}}
form.$submitted = {{form.$submitted}}
NAME:
form.uName.$pristine = {{form.uName.$pristine}}
form.uName.$dirty = {{form.uName.$dirty}}
form.uName.$valid = {{form.uName.$valid}}
form.uName.$invalid = {{form.uName.$invalid}}
EMAIL:
form.uEmail.$pristine = {{form.uEmail.$pristine}}
form.uEmail.$dirty = {{form.uEmail.$dirty}}
form.uEmail.$valid = {{form.uEmail.$valid}}
form.uEmail.$invalid = {{form.uEmail.$invalid}}
</pre>
</body>
</html>
ngClick.