How to dynamically reset an ng-form in Angular

After reviewing the following resources: Reset Form in AngularJS and Angular clear subform data and reset validation, I am attempting to develop a flexible form reset/clear function that would resemble the code snippet below:

$scope.clearSection = function(formName){

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

Is it feasible to create such a dynamic clearing function in Angular where the form name can be dynamically provided as an argument?

Answer №1

Sample plunker: http://plnkr.co/edit/AbCdEfGhIjKlMnOpQrSt

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

Please note: You still must reset the input values!

As stated in the documentation:

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

$setPristine(); Returns the form to its original state.

This function is used to eliminate the 'ng-dirty' class and restore the form to its initial state (ng-pristine class). Additionally, this action applies to all controls within the form.

Returning a form to its original state is beneficial for situations where we wish to 'refresh' a form post-saving or resetting it.

$setUntouched(); Restores the form to its untouched status.

By utilizing this method, the 'ng-touched' class is removed from the form, thereby setting the form controls back to their untouched state (ng-untouched class).

Reverting form controls to their untouched status proves advantageous when reverting the form to its pristine condition.

The use of $setPristine and $setUntouched merely alters the classes of the form controls, not the values themselves. Thus, you are still required to reset the values manually.

Answer №2

There's no reason why it wouldn't work.

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

Answer №3

Absolutely.

When working with JavaScript, you have the ability to retrieve an object's variables by utilizing the [] notation. Allow me to demonstrate this concept through the following example:

var message = 'welcome';
var data = { welcome: 'x' };
console.log(data[message]); // will display 'x'

Therefore, if formName happens to be a string, all you need to do is access the scope property like so:

var form = $scope[formName]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Ways to track down an ajax error response?

Whenever I encounter an AJAX error response with jQuery, the following log is displayed: jquery.js:8630 OPTIONS http://10.0.1.108:8000/api/v1.0/auth/ net::ERR_CONNECTION_REFUSED Object {readyState: 0, status: 0, statusText: "error"} Within my object, the ...

The setTimeout function fails to behave as intended when used in conjunction with synchronous ajax

Within my code, I have a function that is being invoked multiple times due to iterating through an array of length n and creating 'Plants' with synchronous ajax calls. These calls involve querying the Google Maps API, so it is crucial to throttle ...

What is the optimal approach when incorporating images in HTML?

In the process of developing a Webapp, I am working with PHP and JS on the client side and utilizing MySQL on the backend. I am looking to store images when a new database record is added, such as a profile picture. What are the best practices for this s ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

The requested Javascript function could not be found

I have the following JavaScript function that creates a button element with a click event attached to it. function Button(id, url, blockMsg){ var id = id; var url = url; var blockMsg = blockMsg; var message; this.getId = function(){ return id; }; th ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

Creating an Ionic 3 canvas using a provider

I recently followed a tutorial on integrating the canvas API into Ionic, which can be found at this link. However, I encountered an issue where all the canvas-related functions had to be placed within the pages class, making it quite cumbersome as these f ...

Having identical functions with varying IDs and the same variable in Ajax is causing issues

Here, I have two HTML rows with different IDs. When the function ItemSearch() is called, I want to display the search results for both IDs. I am new to JavaScript and AJAX. ***1st Html*** <div class="justlauchSearch"> <div class="input-gro ...

Tips for including parameters in an array of values when using getStaticPaths

I'm trying to retrieve the slug value that corresponds with each number in the getStaticPaths for my page structure: /read/[slug]/[number]. The code I have is as follows: export async function getStaticPaths() { const slugs = await client.fetch( ...

Using jQuery selectors to assign a value to a particular text input field with a matching name

Is it possible to set only the file name field that matches each file input field? I have three text input fields with the same name and three text fields for the file names. function getFileData(myFile){ var file = myFile.files[0]; var filename = ...

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

Guide for transforming an existing AngularJS 2 web application into a Cordova application

I am in the process of building a webapp using AngularJS 2.0 and now I want to convert it into an Android apk so that I can install it on my Android phone for testing. I have no prior experience with developing mobile native apps or converting webapps int ...

Searching for a substring within a larger string in JavaScript

I am trying to create a loop in JavaScript (Node.js) that checks if a string contains the "\n" character and then splits the string based on that character. <content>Hello </content><br /> <content>bob </content><br / ...

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...