Creating Angular 1.5 components with Form and utilizing the $setPristine method

Currently, I am attempting to implement a form within an Angular 1.5 component.

The form is functional as I have successfully achieved model binding and can access the data upon submission. However, the final piece of the puzzle that is missing is the ability to reset the form properly using $setPristine.

I have tried a few different methods, with my initial approach involving passing the form as an argument to the reset function.

In my form.html file:

<form name="$ctrl.userForm">
  ...
  <input class="btn btn-default" type="button" ng-click="$ctrl.reset($ctrl.userForm)" value="Reset" />
</form>

And in my form.component.js file:

ctrl.reset = function(userForm) {
    ctrl.user = {};
    userForm.$setPristine // This returns: Cannot read property '$setPristine' of undefined
};

You can view the full code on Plnkr here.

I also attempted initializing $ctrl.userForm as an empty object during $onInit, but this did not yield the desired result either. Removing the $setPristine line allows the reset function to clear the form's data, however, it does not reset its state from an Angular perspective.

If anyone has any insights or ideas on what might be missing, I would greatly appreciate the help.

Answer №1

In your Plunkr, the entire component is declared below.

function formController() {
  var ctrl = this;
  ...

  ctrl.reset = function(userForm) {
    ctrl.user = {};
    userForm.$setPristine
  };

  ctrl.reset();
}

The error originates from the line ctrl.reset(); where you are calling the method without passing the argument userForm. Additionally, you are using $setPristine incorrectly and there is no need to pass the form as an argument.

I recommend using the form declared in your controller like this:

angular
  .module('application')
  .component('mkForm', {
    templateUrl: 'form.html',
    controller: formController
  });

function formController() {
  var ctrl = this;
  ctrl.master = {};

  ctrl.update = function(user) {
    ctrl.master = angular.copy(user);
  };

  ctrl.reset = function() {
    ctrl.user = {};
    ctrl.userForm.$setPristine();
  };
}

Note: You do not need to call ctrl.reset(); because the pristine state is already the default state.

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

Unspecified behavior for a dropdown menu within an Angular form

I'm a newcomer to Angular and currently struggling with displaying the selected values of form elements in the console. Surprisingly, all other elements get printed except for the select list element which shows up as undefined. Here's an overvie ...

Enhancing the WheelPicker feature in React Native JS by adding a string in front of a specific selected item

I am having an issue with adding the '$' sign before the selected WheelPicker item only. Currently, my code is adding the '$' sign in front of all Picker items. How can I resolve this problem? Thank you for any assistance. https://i.sst ...

Validate AJAX form with additional string input

While I have successfully passed a custom variable and value through ajax during field validation on blur, I am struggling to find a way to include this information when the form is submitted. Currently, in the on blur validation of jquery.validationEngin ...

Two draggable elements and two droppable containers all conveniently placed on a single webpage

My current project involves two sets of draggable elements and two sets of droppable elements. I'm trying to achieve a specific functionality where the first set of draggable elements can only be dropped inside the first set of droppables, while the ...

What is the most effective method for sorting through an array to generate a new array?

Is there a way to filter items from an array based on a specific string and store them in a new array for further manipulation? If so, what would be the most efficient approach to achieve this? Here is the current progress of my code: for (var i = 0; i & ...

React Router relies on a DOM for Browser History to function properly

I am currently developing my app using React.js and express. My main focus right now is setting up react-router-dom for the application. Unfortunately, I encountered a warning when attempting to run the app: Invariant Violation: Browser history needs a ...

Having trouble grasping ES6 concepts with Reactjs?

I am completely new to reactjs and recently followed a tutorial (link: https://www.youtube.com/watch?v=Ke90Tje7VS0). Currently, I am using Windows and following the commands in cmd as instructed in the tutorial: npm i -g <a href="/cdn-cgi/l/email-prote ...

Utilizing XMLHttpRequest alongside a node.js server running on the Express framework

There seems to be an issue with using XMLHttpRequest on my local server created in Node.js and Express, for reasons unknown. Let me illustrate the problem... Here is the Node.js server code: var express = require('express'), app = express.creat ...

What causes the fixed div to appear when scrolling horizontally?

I have replicated this issue in a live example: http://jsfiddle.net/pda2yc6s When scrolling vertically, a specific div element sticks to the top. However, if the window is narrower than the wrapper's width and you scroll horizontally, the sticky elem ...

Server-side form validation in Node.js with client-side feedback handling

Express-form is a validation plugin for node.js/express that offers powerful features. However, the examples and documentation currently only show server-side responses (console.log), which may not be very user-friendly. Two possible solutions come to min ...

What is the best way to store data from multiple selected rows in different datagrids into a single state?

Programming Languages : JavaScript with React, Redux Toolkit, and Material-UI Issue : My goal is to synchronize the selection of checkboxes across multiple datagrids into one central state Attempts Made : I first attempted to manage checkbox selection fo ...

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Angular UI router view is loaded successfully, however, there appears to be an issue

I am currently developing a website using angular ui-router. One of the pages requires passing parameters to another view. I have set up my states as follows: .state('locaties', { url: "/locaties", data: {rule: function($ ...

Implementing a switch feature with enable/disable functionality in a material table using table row data

Is there a way to incorporate an additional action in the Material table and have it included in the React material table along with the element? Furthermore, how can I obtain row data on onChange event while currently rendering it in the state? I would a ...

Can Appcelerator Titanium download and execute JavaScript code dynamically?

I'm looking for a straightforward answer to my question. Is it possible to download and interpret JavaScript code for Titanium as a native app at runtime, or does the code need to be compiled within the application? Thanks in advance! ...

When using Material UI, it is not possible to apply the text-overflow: ellipsis and overflow: hidden properties to multiple

I am new to material UI and here is the current state of my website: view reality of current website This is what I am expecting it to be: what I envision it becoming From the images above, you can see that I want the text inside the circle to be shorten ...

Error Message: While attempting to use the aggregate function, I encountered a CastError where the value "totalsales" could not be cast to an ObjectId for the "_id" path in the "Order" model, as it is of type string

Encountering an error: CastError: Cast to ObjectId failed for value "totalsales" (type string) at path "_id" for model "Order". I followed the code from a tutorial but received this error. Similar error occurred when _id didn't match objectId type, bu ...

Unable to locate NPM-installed modules in the local directory

I've been working on a project and I encountered an issue with locally installed modules using NPM in NodeJS on Windows 10. Despite setting up NODE_PATH, I am still getting errors when trying to require these modules. Here is the structure of my proj ...