Sateesh Kumar Alli Sateesh Kumar Alli - 4 months ago 67
AngularJS Question

Unable to reset an Angular Material design Form from controller

I have an Angular Material design form with 3 input fields which have

required
option. I am not able to reset form to it's default state after clicking submit button. I am using
$setPristine
to change form to pristine state but the red error lines are appearing after submit. Is there any way to get rid of these errors after submitting form.

Thank you.

Codepen Link: http://codepen.io/sateesh2499/pen/pbkjVV

View:

<div ng-controller="AppCtrl" layout="column" ng-cloak="" class="inputdemoErrors" ng-app="MyApp">

<form name="careersForm">
<div class="careersContainer">
<md-content>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Job Title</label>
<input type="text" name="jobTitle" ng-model="careers.jobTitle" required>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Job Location</label>
<input type="text" name="jobLocation" ng-model="careers.jobLocation" required>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Job Category</label>
<input type="text" name="jobCategory" ng-model="careers.jobCategory" required>
</md-input-container>
</div>

</md-content>
</div>
<div class="row text-center">
<div class="col-sm-12">
<md-button class="md-raised" style="width: 200px"
ng-click="postJob()">Submit</md-button>

</div>
</div>
</form>
Pristine: {{careersForm.$pristine}}
</div>


Controller:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])

.controller('AppCtrl', function($scope) {
$scope.careers = {};
$scope.postJob = function(){
// after successful posting
$scope.careers = {};
$scope.careersForm.$setPristine();
}
});

Answer

You can solve it adding $scope.careersForm.$setUntouched(); after calling $setPristine.

I've forked your plunker, where you can see it working. Plunker here

$scope.postJob = function(){
    // after successful posting
    $scope.careers = {};
    $scope.careersForm.$setPristine();
    $scope.careersForm.$setUntouched();
  }

Anyway, I think your code should work...so probably it's a bug.

Hope it helps