Bhumi Singhal
Bhumi Singhal

Reputation: 8297

form field with error not resetting even after form set to pristine : AngularJs

in my HTML :

<form class="form_page login-frm" name="loginForm" novalidate>
   <input type="email" ng-model="data.username" name='username' required autofocus>
   <div class="info-message">
     <small ng-show='(loginForm.username.$error.required || loginForm.username.$error.email) && loginForm.username.$dirty'>The acceptable format for the username includes an '@'.
     </small>
   </div>
   <button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</form>

In Controller:

$scope.cancel = function() {
  $scope.loginForm.$setPristine();
  angular.element(this)[0].loginForm.$setPristine();
  delete $scope.data.username;
};

But after this also, if the username is incorrect and error message is showing and the cancel button is clicked then the error message gets erased but the username field never empties.How to empty the username also.And also after deleting the value why is it visible?

Upvotes: 1

Views: 1516

Answers (2)

hutingung
hutingung

Reputation: 1800

I created plunkr to answer your question. http://plnkr.co/edit/1XblX3?p=preview In more object oriented way you should do this.

var User = function(username) {
    this.username = username;
};
User.prototype.reset = function() {
    this.username = "";
};
$scope.user = new User("Ali");
$scope.cancel = function() {
    $scope.message = "Resetting form";
    $scope.userForm.$setPristine();
    $scope.user.reset();
};

Upvotes: 0

Steve Kl&#246;sters
Steve Kl&#246;sters

Reputation: 9457

Set $scope.data.username to the empty string or to undefined, instead of deleting it. You also do not need the line with angular.element(...) in your controller.

Upvotes: 1

Related Questions