1

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?

4
  • 2
    $scope.data.username = '' ? Commented May 4, 2014 at 11:55
  • isnt deleting the value a better approach. You see i have other fields too and deleting those workss for me if there is no error on those Commented May 4, 2014 at 12:13
  • No. The model is centre to an angular app and if you start carving chunks out of it then you will suffer. Add a function called reset to the data object and set all the values to null or empty string or 0. Commented May 4, 2014 at 12:21
  • EUREKA : if the form field is errorenous then the ng-model does not update. Commented May 5, 2014 at 5:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

isnt deleting the value a better approach. You see i have other fields too and deleting those workss for me if there is no error on those
Deleting means the property doesn't exist, which means JavaScript will search up the prototypal chain. In the case of a form, this is rarely what you want. Setting it to an empty or undefined value is, in my opinion, cleaner.
0

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();
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.