Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting form after submit in Angularjs

Hi I have a form which does update on button click.

 $scope.action = "Update";
  var id = $routeParams.editId;
  scope.item = updateRecord.get({ id: id });

Once the item is updated it doesn't remove the entered information in the form fields. I was wondering what is available in angularjs to add in the above code after udpating so that it also clears to form. Thanks

like image 201
J. Davidson Avatar asked Feb 05 '14 07:02

J. Davidson


People also ask

How do you make form reset after submit?

To clear an input field after submitting:Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.

How would you reset all objects on a form in angular?

In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.

How do I reset form data?

reset() method restores a form element's default values. This method does the same thing as clicking the form's <input type="reset"> control. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled .


4 Answers

You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:

$scope.currentRecord={};

EDIT

As ToodoN-Mike pointed out, don't forget to set

$scope.formName.$setUntouched()

The $touched flag was introduced in angular 1.3.

like image 119
Mohammad Sepahvand Avatar answered Oct 05 '22 16:10

Mohammad Sepahvand


At the bottom of your submit function's body run this code below.

// Reset the form model. vm.project = {}; // Set back to pristine. vm.form.$setPristine(); // Since Angular 1.3, set back to untouched state. vm.form.$setUntouched(); 

"vm.form" is my form name.

For more info have a look at this docs page: https://docs.angularjs.org/api/ng/type/form.FormController

like image 30
Samuel R Avatar answered Oct 05 '22 15:10

Samuel R


This worked for me.

viewModel.data = {};
$scope.formName.$setUntouched();
$scope.formName.$setPristine();
like image 21
Pete Avatar answered Oct 05 '22 16:10

Pete


1) To Remove the values in Form Fields and to reset you can use $setPristine();

$scope.formName.$setPristine();

2) Next, to set the form to Untouched State too use $setUntouched();

(If you have required fields in your form Fields and also if you are using ng-messages then if you don't use the below function those fields will show error.)

$scope.formName.$setUntouched();
like image 42
Ranger Avatar answered Oct 05 '22 15:10

Ranger