What causes my Angular form to be labeled as dirty even after setting a control to pristine manually?

I have recently developed a new directive:

app.directive("customDate", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attributes, controller) {          
            scope.$watch(function () {
                return controller.$modelValue;
            },
            function (newVal, oldVal) {
                if (newVal !== oldVal && newVal) {
                    var format = attributes.date || "dd-MM-yyyy";
                    var parsedDate = new Date(newVal);

                    parsedDate = $filter('date')(newVal, format);

                    controller.$setViewValue(parsedDate);
                    controller.$setPristine();
                    controller.$render();
                }
            });
        }
    }
}])

To use this new directive, simply include it in your HTML like so:

<form name='myForm'>
    Date: <input type="text" data-ng-model="event.Date" name="Date" custom-date />
</form>

In my scope, I have a handy function that determines the save button's state:

scope.canSave = function () {
    return scope.myForm.$valid && scope.myForm.$dirty;
}

Interestingly, despite calling controller.$setPristine() in the directive, the form controller does not register this change. This results in form.$dirty being true, while form.Date.$dirty remains false.

Why is this happening and what steps can be taken to ensure that Date is recognized as clean by the form?

Answer №1

After much searching, I stumbled upon a solution involving parsers and formatters:

app.directive("customDate", ['$filter', function ($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attributes, controller) {
            controller.$parsers.unshift(function (value) {
                if (!value) {
                    return;
                }

                var format = attributes.customDate || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })

            controller.$formatters.unshift(function (value) {
                if (!value) return;

                var format = attributes.customDate || "dd-MM-yyyy";
                return $filter('date')(value, format);
            })
        }
    }
}])

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 comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Looping through multiple AJAX calls

I have come across numerous questions on this topic, but I am still struggling to find a solution that will make my code function correctly. There is a specific function for calling AJAX that I am unable to modify due to security restrictions. Here is how ...

What is the best way to make a div automatically scroll to the bottom of its height in

I've spent a considerable amount of time searching for an answer to this question, but unfortunately, none of the solutions I found were suitable for my specific scenario. Currently, I am developing a Chat Application and one key feature is displayin ...

In a set of strings, locate the two shortest ones, remove them, and then add them back to the end repeatedly until there is only one string

I've been struggling with a coding challenge for a couple of hours now and could really use some help. Here are the detailed instructions: Take an array of strings and create a single string by following these steps: Repeat the following steps as lo ...

PWA notifications not working on iOS with FCM even after multiple tries

I am currently utilizing Firebase Cloud Messaging in order to send daily notifications to iOS users who have installed a PWA app. Upon testing, I noticed that each token is limited to receiving only 2 notifications successfully. Any attempt beyond that w ...

Troubleshooting issue with changing label text using innerHTML in JavaScript

In need of some advice regarding a javascript function I've been working on: function validateFile() { var file = document.getElementById('fuCSV'); if (file.value == "") { document.getElementById(&apo ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

"Save an HTML file as a .txt document on your personal server

After coming across a code that grabs information and saves it in a .txt file, I encountered an issue where clicking the "SAVE" button downloads the file to my personal computer rather than saving it on the local server. To address this problem, I watched ...

Utilizing dropdown menus in React to refine data pulled from an API

How can I use a dropdown menu to filter results from an API? Currently, my select tag looks like this: <select value={selectMonthFilter} onChange={e=> setSelectMonthFilter(e.currentTarget.value)}> {console.log(selectMonthFilter)} <opti ...

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

Is there a way to integrate the AJAX response from JavaScript into a JavaScript function?

I am having a nightmare trying to solve this issue. I am currently working on an app using phonegap and have integrated highcharts for creating graphs. The graph displays properly, but the tooltip is not working as expected. Below is the code snippet that ...

The .NET controller does not receive traffic for the GET method

Having some trouble populating a table with JSON data using angular ng-repeat. No errors are showing up in the console, and my breakpoint in the .NET Controller isn't being triggered. Here's the code for the App Controller: var app = angular.mo ...

Expanding on the nested document in mongoose

I have been working on setting up a nested mongoose document configuration in the following manner: models/data.js var mongoose = require('mongoose'); var addresses = new mongoose.Schema({ "street": String, "city": String, "state": Stri ...

Calling a controller method from within a directive in AngularJS is not possible

I'm currently developing a hybrid Ionic1 app and I am facing an issue with calling a controller method from within a directive. In the directive, I can pass variables from the controller (like the variable apps), but I am unable to call the removeCred ...

Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS. The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops. Here's the code I've be ...

displaying a confirmation using jQuery in CodeIgniter

Hello everyone, I am a beginner in CodeIgniter and I am seeking assistance. I am attempting to create a confirmation message (div id="delmsg") using jQuery when deleting a record from MySQL database. The delete operation is functioning properly, but the me ...

HTML Date Form: Setting the Start Date to Tomorrow with JavaScript

Is there a way to restrict the start date to tomorrow's local date? I'm having trouble with the code below: <form method="POST"> <div> <label for="s2">pickup_date</label> ...

Combining data from various JSON files to create dynamic charts with Highcharts

At this moment, my Highchart code is set up in a way where I want to replace the static data-series values within the HTML file with information loaded from a JSON file. The current code appears as follows: <!doctype html> <script type="text/jav ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

Adjust the HTML size before converting it to a PDF using the jspdf .html() function

Currently, I am exploring the process of resizing an HTML element using the jsPDF method called .html(). I attempted to implement the following code but found that the width parameter did not have any impact on the final output. Since there is no officia ...