Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview

Here is the code snippet:

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.data={fullName:''};

  $scope.submit=function(){
    console.log('submit')
    $scope.myForm.$setPristine();
    $scope.myForm.$setUntouched();
    $scope.data={fullName:''};
  }
});

HTML:

<body ng-controller="MainCtrl">
<form name="myForm" novalidate>
<div>
    <label class="control-label">Name</label>
    <input
            name="full_name"
            type="text"
            ng-model="data.fullName"
            ng-required="true">

    <p ng-if="myForm.$submitted && myForm.$invalid">Validation message</p>
</div>
<button ng-click="submit()" type="submit">
    Submit
</button>
</form>
</body>

The issue I'm facing is that even after entering a name in the input field and clicking Submit, the validation message remains visible. How can I reset the model, form, and validation to prevent this?

I have tried using $setPristine() and $setUntouched(), but it hasn't worked for me.

Is there a way to achieve this in AngularJS? Thank you!

Answer №1

It is surprising that $setpristine() does not update the value of $submitted.

While this solution may not be the most elegant, it appears to get the job done:

app.controller('MainCtrl', function($scope, $timeout) {
  $scope.data = {
    fullName: ''
  };
  $scope.submit = function() {
    console.log('submit')
     $scope.data = {
      fullName: ''
    };
    $timeout(function() {
      $scope.myForm.$setPristine();
      $scope.myForm.$setUntouched();
      $scope.myForm.$submitted = false;
    });   
  }
});

Check out the demo here!

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

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

Transferring a value via AJAX that has been modified by a previous AJAX call

In my form, users input values which are used to calculate a result. The calculation is performed through AJAX calls triggered by onchange events on the user-edited fields. This process works as expected. However, there is a hidden field that also gets up ...

Creating a link that triggers a submit event

I am stuck with this piece of code: <form name="ProjectButtonBar_deleteProject_LF_3" action="" method="post"> <a class="buttontext" href="javascript:document.ProjectButtonBar_deleteProject_LF_3.submit()">...</a> Instead of directly subm ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...

Resizing Div elements in React

I am currently working on a Drawer navigation feature and I am exploring the option of enabling mouse drag resize functionality. To achieve this, I have included a div element where I listen for the onMouseDown event. Once triggered, I then add an event li ...

Can you show me the steps for linking the next method of an EventEmitter?

After emitting an event, I am looking to run some additional code. Is there a method to chain the .next() function in this way? @Output() myEvent = new EventEmitter<string>(); this.myEvent.next({‘test string’}).onComplete(console.log('done& ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Disappearing Facebook share button: A common occurrence when navigating in Nuxt.js (Vue.js)

Within my nuxt.js web app, utilizing version 2.15.7, I have integrated a Facebook share button by following the instructions outlined in this comprehensive code example. Upon initial load of the application, the Facebook share button appears as expected. ...

Tips for locating the bug line or file in Angular 2

I am currently following the Angular hero tutorial, and I have reached the Routing step. However, I encountered an issue with my script not working properly. The default template only displays "Loading..." text, indicating that there is an error in one of ...

Using JavaScript to sort data within specific timeframes

How can I extract data based on timestamps greater than 06? "use strict" const data = [ {timestamp: "2020-04-23 05:05", totalAvg: 2.596211180124224}, {timestamp: "2020-04-23 05:10", totalAvg: 3.22052273203436}, {timestamp: "2020-04-23 05:15", t ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

How to retrieve an element in jQuery without using the onclick event listener

I'm looking to extract the element id or data attribute of an HTML input element without using the onclick event handler. Here is the code I currently have: <button class="button primary" type="button" onclick="add_poll_answers(30)">Submit</ ...

JsTree drag and drop feature malfunctioning: Icons disappear when dragging items

I am currently utilizing JsTree with the drag and drop plugin enabled in conjunction with an angular directive, https://github.com/ezraroi/ngJsTree. Everything appears to be functioning correctly, however, when I move a node, it does not visually show as ...

Failure to Reach AngularJS ng-click Function

When trying to add a new product to the product list, I am facing an issue. The products load correctly but the ng-click function is not being triggered. (The alert I set up in the addProduct function is not appearing). HTML <div ng-controller="Produc ...

Upon submitting the form, the dynamic dependent drop-down list fails to offer any available options

Hey there, I've got a form with two drop-down lists: id="dd-1" & id="dd-2". The options in id="dd-2" are generated from the database based on what's selected in id="dd-1"; I'm using onChange=getChildOf(this.value) in id="dd-1" for this ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

Is there a way for me to store the message I sent using discord.js in a variable?

I'm looking to send a message in the channel and then react to it by getting that message for a message reaction. bot.sendMessage({ to: channelID, message: '@everyone\n' + message.slice(16) + '\n\nThis message is a ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...