Skip to content Skip to sidebar Skip to footer

How To Properly Clean Form With Invalid Input From Angularjs Controller?

I have an AngularJS form that contains - among other fields - one of type url. The latter is important as this forces the corresponding input to be a valid URL. Under certain condi

Solution 1:

Specify the type of your button as reset. That will not only call the ngClick function, it will also clear the content of the HTML form.

<button type="reset" ng-click="resetFormData()">Reset</button>

Solution 2:

I think this solution is moderately elegant: your plnkr reviewed The big difference is the initialization of your model object.

I think things gets messed up when a variable becomes undefined, it doesn't get updated anymore.. it should be connected (veeeery) deeply with how validation works (docs link)

Returning undefined in that case makes the model not get updated, i think this is exactly what happens behind the curtain

PS: you can recycle resetImplicitly for all your forms in the webapp :)

Solution 3:

After trying several answers without success in similar questions, this worked for me.

In my controller:

$scope.cleanForm = function() {
  $scope.myFormName.$rollbackViewValue();
};

Just call with some ng-click or any way you want.

Cheers

Solution 4:

The Thing is tag is of type "url" which means if user will enter specifically a valid url then only it will set values of model

If user will expicitly reset it which means setting model values to "" will again make textbox empty .

It is looking like it is setting the values but actually not ,so when you set its value to "" .Angular will set modal value to "" Lets take another example : put replace "text" with "email"

<inputtype="email" ng-model="formData.name" />
      <br />URL:
      <inputtype="url" ng-model="formData.url" />
      <br />

In above code If you will enter invalid email it will not set the values of email's model.

Solution 5:

You probably need to make a copy of the model in its pristine state and set the model to pristine when you reset.

There's a good example here:

http://www.angularjshub.com/examples/forms/formreset/

Post a Comment for "How To Properly Clean Form With Invalid Input From Angularjs Controller?"