Dynamically reset ng-form in Angular

I took a look at the following: Reset Form in AngularJS and Angular to clear subform data and reset validation from them I am trying to create a dynamic reset / clear form that will look something like this:

$scope.clearSection = function(formName){ $scope.formName.$setPristine(); $scope.formName.$setUntouched(); }; 

Is it possible to create a dynamic cleanup function like this in angular where the form name is dynamically passed to this function?

+5
source share
3 answers

Plunkr example: http://plnkr.co/edit/lnGym0vKsANL6oks30RG

 $scope.resetForm = function(formName) { var form = $scope[formName]; form.$setUntouched(); form.$setPristine(); } 

Note. You still need to reset the input values!

According to the docs:

https://docs.angularjs.org/api/ng/type/form.FormController

$ setPristine (); Sets the form to its pristine state.

This method can be called to remove the class 'ng-dirty' and set the form to its original state (ng-primitive class). This method also applies to all controls contained in this form.

Setting the form back to its pristine state is often useful when we want to β€œreuse” the form after saving or resetting it.

$ setUntouched () ; Sets the shape to an untouched state.

This method can be called to remove the ng-touched class and the settings form the controls to their untouched state (ng-touched class).

Setting the control form back to their pristine state is often useful when setting the form back to its pristine state.

$ setPristine and $ setUntouched change only the form control classes, not the values. This means that you still need to reset the values.

+4
source

I don’t understand why not.

 $scope.clearSection = function(formName){ var frm = $scope[formName]; frm.$setPristine(); frm.$setUntouched(); }; 
+3
source

Well yes.

In JavaScript, you can access object variables using the [] notation. Take the following example

 var str = 'hello'; var obj = { hello: 'a' }; console.info(obj[str]); // outputs 'a' 

so if formName is a string, you can just get the scope property with

 var form = $scope[formName] 
+1
source

Source: https://habr.com/ru/post/1235759/


All Articles