7

I have taken a look at the following: Reset Form in AngularJS and Angular clear subform data and reset validation from these I am trying to create a dynamic form reset/clear function which would look like something like the following:

$scope.clearSection = function(formName){

    $scope.formName.$setPristine();
    $scope.formName.$setUntouched();
};

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

3 Answers 3

6

Example plunkr: 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 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form.

Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

$setUntouched(); Sets the form to its untouched state.

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

Setting a form controls back to their untouched state is often useful when setting the form back to its pristine state.

$setPristine and $setUntouched only change the classes of the form controls, not the values. That means you still need to reset the values.

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

3 Comments

Thanks for the heads up on the resetting I realized that after posting the question. Just a quick extra question. Is it possible for me to just reset the object as linked in my question. aka object: {manythingshere: "asdasda"} to object: {} will this remove/reset the validation?
Yes it is, just reset the object to {}. Example plunkr: plnkr.co/edit/cGgnbtwnc47BHnFGB3QA
Marked this as the accepted answer because of the "in-depth" explanation as well as a link to the docs.
3

I don't see why not.

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

Comments

1

Well yes.

In JavaScript you can access variables of an object 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 simply get the property of the scope using

var form = $scope[formName]

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.