hh54188
hh54188

Reputation: 15656

AngularJS: How can I $setPristine after submit the form

I want some input element be $setPristine when I submit the form. Because after I submit the form, I would empty the model bind to the input element, in case of user can totally input something new again. But once I empty the model, the input element would empty too, so the validate information would show, for required.

So I want $setPristine after submit the form. I figure out two ways:

One:

I use expression in the ng-submit, like:

<form ng-controller="FormController" name="userForm" ng-submit="userForm.$valid?submitForm(),userForm.keywordsInput.$setPristine(): ''">

But this syntax seems wring because angular report error information in the console.

Two

I could pass form to the submit function, then $setPristine in the submit function :

$scope.submit = function (form) {
    form.keywordsInput.$setPristine()
}

But I also don't this is a good practice, because in the angular official reference site, it suggest:

Do not use controllers to:Manipulate DOM.

Is this way a kind of manipulating DOM?

So is there a better way to achieve this job?

Upvotes: 1

Views: 1219

Answers (2)

Soham Mehta
Soham Mehta

Reputation: 604

When you submit the form, you must have set some function to run in the "ng-click" attribute

Add formName.$setPristine(); after it

Upvotes: 0

Stallion
Stallion

Reputation: 77

I had the same issue logging undefined $setPristine(). But,in the view it works.

<button class="button button-stable button-block " type="submit" ng-click="register(registerData);formName.$setPristine();"> Submit </button>

Upvotes: 0

Related Questions