Is AngularJS not able to effectively manage the button type "reset"?

I currently have the following code snippet:

<form name="editor">
    <h2>Create/Update</h2>
    {{ editor.title.$error.required }}
    <div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, 'has-success': editor.title.$valid }" class="form-group">
        <input type="text" name="title" ng-model="project.title" placeholder="title" required class="form-control">
        <span class="input-icon fui-check-inverted" ng-show="editor.title.$valid"></span>
    </div>
    {{ editor.description.$error.required }}
    <div ng-class="{ 'has-error': editor.description.$invalid && editor.description.$dirty, 'has-success': editor.description.$valid }" class="form-group">
        <textarea name="description" ng-model="project.description" placeholder="description" required class="form-control"></textarea>
        <span class="input-icon fui-check-inverted" ng-show="editor.description.$valid"></span>
    </div>
    <button ng-click="save()" type="submit" class="btn btn-primary btn-embossed">Save</button>
    <button type="reset" class="btn btn-inverse">Reset</button>
    <a href="#/">Back</a>
</form>

I am currently following a tutorial on "JavaScript Projects" from the main page of Angular's website. I recently added a reset button to detail.html, but I am facing an issue with its behavior. Whenever I manually clear the fields, the validation fails. However, when I click on the reset button, the fields are cleared but the form remains valid. Could this be a bug in Angular? How can I resolve this issue?

Answer №1

Perhaps what you are seeking is $setPristine();

$setPristine();

This function sets the form back to its original clean state.

By calling this method, you can eliminate the 'ng-dirty' class and restore the form to its pristine condition (ng-pristine class). The reset will also extend to all elements within the form.

Returning a form to its pristine state can be valuable when wanting to utilize a form again after saving or resetting it.

source: http://docs.angularjs.org/api/ng/type/form.FormController

JavaScript Example

$scope.data = {
    "username": "", 
    "password" : ""
};

$scope.reset = function() {
  $scope.data.username = "";
  $scope.data.password = "";
  $scope.form.$setPristine();
};

Markup Example

<form name="form" id="form" novalidate>
        <input name="username" ng-model="data.username" placeholder="Name" required/>
        <input name="password" ng-model="data.password" placeholder="Password" type="password" required/>
        <div>
            <hr />
            <button class="button" ng-click="">Login</button>
            <button class="button" ng-click="reset()">Reset</button>
        </div>
</form>

Demo http://plnkr.co/edit/xTQLQH8mCCkY0tIX6n8Y?p=preview


Update : streamlining the solution

To simplify the process without using the controller function reset(), consider setting type="reset" like before, but still executing $setPristine() on ng-click

<button class="button" type="reset" ng-click="form.$setPristine()">Reset</button>

new plunk: http://plnkr.co/edit/tNKPyyMboAQjeURn6m6W?p=preview

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

Issue encountered during the compilation process using Ionic version 2.0.0-beta.30

After updating my ionic CLI version from 2.0.0-beta.25 to 2.0.0-beta.30, I tested a simple app with the following command and it worked perfectly: ionic start nameofmyapp --v2 However, when attempting to build the app for the android-platform, an error o ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

What is the best way to deploy a REST API utilizing an imported array of JavaScript objects?

I have been using the instructions from this helpful article to deploy a Node REST API on AWS, but I've encountered a problem. In my serverless.yml file, I have set up the configuration for the AWS REST API and DynamoDB table. plugins: - serverless ...

Having trouble getting Jquery autocomplete to function properly with a complicated array?

I started with the guidance provided in this post, which was successful. To investigate why it's not functioning, I made a JsFiddle but couldn't figure out the issue. Even when trying to search for results using the first letter of the last name ...

ASP.NET Rewrite Rule Implementation

I have set up a rewrite rule in IIS for my single page app, using Angular UI Router to serve the project. However, when sending a request to an API service, it does not call the service and redirects me to a different page specified in the rule's acti ...

The left border is failing to appear on the Td element

When attempting to add border styling to td elements, the left border is not displaying correctly. This issue seems to vary across different browsers. Here is the HTML code: <table class="table-bordered"> <thead> <tr> ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

Utilizing JQuery's $(document).ready() function following a window.location change

I'm having trouble getting a JavaScript function to run after being redirected to a specific page like "example.com" when the DOM is ready for it to work with. Unfortunately, it seems that $(document).ready() is running before "example.com" finishes l ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

What is the best way to duplicate a text using a button in ReactJS?

Hey there, I'm working with an array and trying to figure out how to copy the text in a p element ({item.adress} => this is part of an array item) when a button is clicked. Could you lend me a hand? import classes from './CryptoBox.module.css& ...

The resource being requested is missing the 'Access-Control-Allow-Origin' header - Issue with Pinterest OAuth implementation

While working on implementing OAuth for Pinterest, I successfully retrieved the access code. However, when attempting to perform a GET /v1/me/ request, I encountered an error in the Chrome console: XMLHttpRequest cannot load . No 'Access-Contro ...

What is the best way to incorporate external scripts into a Node.js project?

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> What is the process for adding an external library to a node.js application? I am seeking assistance on how to integrate the following library into my ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Using JavaScript to make an AJAX call to a different domain while bypassing the Content Security Policy restrictions

While parsing a web page, I need to initiate an AJAX call to my localhost depending on the content. The purpose is to exchange data using a PHP script on my localhost, possibly in JSON format (still under testing). This process is part of a plugin that I ...

Change the ng-model of the initial controller when a button is clicked in a separate controller

I am working on an AngularJS application that has two controllers. I am facing an issue where I need to update the ng-model of an input field in the first controller by clicking a button in the second controller. Accessing the $scope of the first controlle ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

Ways to determine whether a DOM textnode is a hyperlink

Is there a more foolproof method for determining if a DOM textnode represents a hyperlink? The code snippet below currently only checks if the node is directly enclosed in an anchor tag, which may not be sufficient if the <a> element is higher up i ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...