Directive in AngularJS fails to trigger upon form reset

I encountered an issue with a directive used within a form, specifically when clicking on a button with the type reset. The problem can be replicated on this stackblitz link. The directive I'm using is quite simple - it sets the input in an error state if the entered value is less than 1900. It's worth noting that I am unable to change the type of the button, it must remain as type=reset.

To see the expected behavior of the directive:

  1. Input '100' into the field => you should see the input display an error
  2. Input '2000' into the field => the input should no longer show an error

To observe the bug in the directive's behavior:

  1. Input '100' into the field => the input will show an error
  2. Click on the reset button => the input will be cleared, but the error state persists, even though it should have been removed

Below is the HTML code snippet:

<form name="dateForm">
    <div class="form-group" name="dateForm">
        <label for="usr">Name:</label>
        <input type="text" class="form-control" id="year" name="year"
               valid-year="true" ng-model="$ctrl.year" year-min="1900">
    </div>
    <button type="reset" class="btn btn-primary">Reset</button>
</form>

This is the corresponding JS code:

angular.module('app', requires)
.directive('validYear', function() {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            if (attrs.validYear === 'true') {
                if (!modelCtrl) {
                    return;
                }
                modelCtrl.$parsers.push(function (value) {
                    console.log('--> call to directive');

                    if (angular.isDefined(attrs.yearMax) && parseInt(value) > parseInt(attrs.yearMax)) {
                        modelCtrl.$setValidity('validYear', false);
                    } else {
                        modelCtrl.$setValidity('validYear', true);
                    }
                    if (angular.isDefined(attrs.yearMin) && parseInt(value) < parseInt(attrs.yearMin)) {
                        modelCtrl.$setValidity('validYear', false);
                    } else {
                        if (angular.isDefined(attrs.yearMax) && parseInt(value) > parseInt(attrs.yearMax)) {
                            modelCtrl.$setValidity('validYear', false);
                        } else {
                            modelCtrl.$setValidity('validYear', true);
                        }
                    }
                    return value;
                });
            }
        }
    };
});

Answer №1

Initially, your validation directive is quite unusual - if you update the value from the controller, it won't function properly... Quite odd. (Is this intentional?) I recommend referring to the AngularJS documentation for guidance on how to correctly implement validators.

Moreover, your main issue lies not in the validation process but rather in the fact that the 'reset' button does not reset the model value. It would be wise not to depend solely on built-in functionalities; instead, consider customizing the behavior of the reset button:

<button type="reset" ng-click="$event.preventDefault();$ctrl.year=null"...

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

An issue occurred while attempting to read words from JSON file

My current issue involves loading words from JSON into my webpage. The images are functioning properly, thankfully. I have already successfully loaded the necessary images through JSON onto my webpage. However, I am still in need of loading words through ...

In what way can I indicate parsing "per dataset" using Chart.js?

I'm currently exploring the usage of the yAxisKey option in ChartJS while defining a dataset. However, I'm encountering difficulties in replicating this specific example from the documentation. Despite my efforts to search for issues related to y ...

JavaScript's native innerHTML function is unable to access the content generated by Vue

I have been struggling with extracting the content from a specific div element in my HTML code. <div id="output" ref="output_data"> <h1>{{ information }}</h1> </div> I attempted to retrieve the contents using ...

Maximizing the potential of selectors in jquery.min.js

Can anyone explain what the purpose of selectors = {cacheLength: is in the jquery.min.js file? Additionally, I'd like to know if it is feasible to modify the value of cacheLength using jQuery. =ga.getText=function(a){var b,c="",d=0,f=a.nodeT ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

Automatically populate a dropdown list based on the selection made in another dropdown menu

I'm populating a second textbox based on the input of the first textbox in auto.jsp. Now, I want to automatically populate a combo box as well. How can I achieve this? Specifically, I want to autofill the second combo box based on the selection made i ...

The argument for the e2e test is invalid because it must be a string value

Currently, I am conducting an end-to-end test for an Angular application using Protractor. However, I encountered an error while running the test for a specific feature file. The UI value that I am checking is - WORKSCOPES (2239) Below is the code snippe ...

POST method error 400 encountered

Whenever I execute my ajax jquery function, I encounter a 400 error Here is my code. All Postman tests pass successfully, but when the web app runs, it fails. I'm not sure if it's a coding issue or something related to HTML5. Can anyone offer as ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

React is displaying [object Object] instead of the intended value on the webpage. What steps can be taken to resolve this issue?

I have attempted to retrieve data from an API and am currently working on displaying this data within a table cell inside a component. Instead of rendering the original data, React is displaying [object Object]. I tried using the join() method with commas ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Different Slide Library Fullpage.js

Is it feasible to have two sections with the same slide in fullpage.js? For example, if I'm currently on slide 1 of section 1 and then move to slide 2 of section 1, can section 2 automatically switch to slide 2 as well? I'm curious if this funct ...

Guide on attaching an onclick function to a search bar

I found a search bar code on this website and I want to enhance it by adding a function that redirects users to a URL when they click on the search icon. Here is the existing code: <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> ...

Ways to utilize the map() function with data retrieved from an axios response?

Utilizing axios for data retrieval from the server and then storing it in the state. However, when attempting state.map( post => {console.log(post)} ), no output is displayed. The technologies being used are Express, Mongoose, NextJS, and Axios. My ap ...

Unable to render the ng-repeat child scope attribute

I am working on displaying a list of data records using ng-repeat. Each data object entry (referred to as a coupon) needs to have specific properties ($scope.etabName and $scope.etabDistance) extracted from it, calculations performed, and the results displ ...

Enhance your AngularJS application with the powerful Complexify directive

Can someone assist me in creating an AngularJS directive using Complexify for a password meter? Here is what I need: <input type="password" ng-model="password" /> <password-meter value="password" complexity="complexity"></passwordMeter> ...

What is the best way to populate an array with JSON data using jQuery?

As a newcomer to jQuery, I decided to experiment with the getJSON function. My goal was to extract the "id" section from a JSON file and store it in an array called planes using jQuery. This array would then be utilized in an autocomplete function to popul ...

What is the best way to rotate a mesh group around the axis of a randomly selected 3D element within the Three.js environment?

I'm currently delving into the intricacies of three.js in order to experiment with a basic mechanism. My end goal is to visualize board tilt (front view) in relation to axle orientation (plan view) for different designs on an XY plot, although that&ap ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...