md- The datePicker component consistently encounters errors with Date instances

I encountered an issue where the error message

The ng-model for md-datepicker must be a Date instance. Currently the model is a: string
appeared. I am utilizing moment.js library to handle dates.

Within the view section:

<md-datepicker ng-model="Model.currentContact.getSetIncorporated" ng-model-options="{ getterSetter: true }" md-placeholder="Enter date"></md-datepicker>

And in the model section:

Contact.prototype.getSetIncorporated = function(date) {
        if (arguments.length) {
            this.company.information.incorporatedObject = date;
            this.company.information.incorporated = moment.utc(date).format('X');
        }
        // rest of the function...
    }

I have also attempted using different methods like mdLocale.formatDate and parseDate. The current version looks like this:

$mdDateLocale.formatDate = function(date) {

            return moment(date).format('YYYY/MM/DD');
        };

        $mdDateLocale.parseDate = function(dateString) {

            var m = moment(dateString, 'YYYY/MM/DD', true);
            return m.isValid() ? m.toDate() : new Date(NaN);
        };

The server sends a date string like this: 2016-09-10T22:00:00.000Z

Converting this string to a Date object using new Date() displays the correct result in the mdDatePicker but triggers an error message

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
, causing issues on my page.

Answer №1

It appears to be a simple issue. The problem lies in passing a string instead of a date to

Model.currentContact.getSetIncorporated
.

An example illustrating the issue can be found here - CodePen. The error message is displayed in the console.

angular.module('MyApp',['ngMaterial'])

.controller('AppCtrl', function() {
  this.myDate = new Date();
  this.myDate = this.myDate.toString(); // To resolve, comment out this line
});

You may find assistance on how to differentiate between a string and a date object in this related question - How to check whether an object is a date?.

Update:

The error message stating

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached.

is likely due to the

Contact.prototype.getSetIncorporated
function returning a Date when a string is required by the ng-model.

A potential workaround for this issue can be found here - CodePen.

angular.module('MyApp',['ngMaterial'])

.controller('AppCtrl', function($scope) {
  this.myDate = new Date();

  this.test = function () {
    return new Date();
  }  
  this.testModel = this.test();
});

HTML Markup

<div ng-controller="AppCtrl as vm" ng-cloak="" class="datepickerdemoBasicUsage" ng-app="MyApp">
  <md-content>
    <md-datepicker ng-model="vm.testModel"  ng-model-options="{ getterSetter: true }" ng-change="change()"></md-datepicker>
  </md-content>
</div>

Answer №2

When utilizing the moment library, remember to retrieve the _d property from moment:

    var _parseStringToDate = function (stringDate) {

        var date;
        if (typeof stringDate === 'string') {
            date = moment(stringDate)._d;
        }

        return date;
    };

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

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

Is there a proper method for populating an HTML text with values from a form?

As a newcomer, I could really use some guidance here :) I'm trying to populate text with various words, numbers, and calculation results from a form. This is my initial attempt for just one field/word, and it appears to be functioning correctly. Do y ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Monitor the change in FileReader().readyState using AngularJS

Below is the AngularJS code I have written to read a local file. var files = document.getElementById("file"); files.addEventListener("change", handleFile, false); function handleFile(event) { SpinnerService.upload(); // Display loading spinner ...

AngularJS Error: [$injector:modulerr] occurred when the AngularJS injector was

Encountering an error in the browser: Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector>/modulerr? The script app.js looks like this: var sampleApp = angular.module('myApp',[]).config(function($routeProvider){ ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

Error Encountered During Global Installation of NodeJS

I'm attempting to create a Node module that, when installed globally with the -g flag, can be run with a single command from the terminal. Although the tutorials I've followed suggest it should be straightforward, I seem to be missing something. ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Leverage the Power of JSON Data Manipulation in WordPress with Angular JS and the WordPress JSON

After testing code in this particular post and making some adjustments, I encountered an issue with obtaining a JSON object from the API of my blog created using the WordPress JSON plugin. URL of API from BLOG (NOT FUNCTIONING): URL from W3C example (WO ...

When using Angular's *ngFor directive with the async pipe, the DOM does not reflect changes from an API

I'm having trouble with the offers$ observable in my Child component. When it is updated using a post request, the changes are not reflected on the DOM when using *ngFor and async pipe. However, if I subscribe to the get request instead of using an ob ...

Display toggle malfunctioning when switching tabs

I am currently working on implementing a search function with tabbed features. Everything seems to be displaying correctly without any errors. However, the issue arises when I try to click on any tab in order to show or hide specific content from other tab ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Using jQuery AJAX to Populate a Textbox and Dropdown Menu

I am new to using JQuery AJAX, so I am still learning the syntax. Currently, I am retrieving values from a database and populating a dropdown box. What I would like AJAX to do is fill in three other fields with hardcoded information when a selection is mad ...

Troubleshooting the Autocomplete Problem in Kendo UI AngularJS with ngMap

My current challenge involves attempting to combine the autocomplete feature of ngmap with Kendo UI. However, I am encountering an issue where the placeChanged event is not triggering and the autocomplete widget is not displaying. The input placeholder i ...

Unable to convert the existing JSON array into the specified type

I've been struggling to find a solution to this problem, even though I've come across similar topics that have been asked before. Below is a sample Json that I'm posting to a web API controller: { "AppointmentId ":2079, "ma ...

Exporting Typescript to Javascript files

I have created a sample TypeScript object with the following code: declare const S3 = "https://s3.amazonaws.com/xxx/icons"; declare const SVG = "svg-file-icons"; declare interface MyIcons { "image/jpeg": string; "image/jpg": string; } export const F ...

What is the best way to modify the appearance of the button?

I'm attempting to change the appearance of buttons at the top of a webpage to be square and blue. I have jQuery code for this purpose, but it doesn't seem to be functioning correctly. Here is the snippet of code I am using: $(document).ready(fu ...

Error: The module '/@modules/vue.js' does not export a 'default' value as requested by the syntax

I'm encountering an issue with Vee Validate form validation in Vue.js. As a beginner, I am struggling to grasp the import syntax. After installing vee-validate using npm i vee-validate --save and placing it in my node_modules directory, I proceeded to ...

Leverage shared techniques and libraries across two different projects

I have a NodeJS project set up on Firebase cloud functions, with our backend service (ExpressJS) as an HTTP function and some cron functions. The project structure looks like this: /project (the main directory for all cloud functions) - package.json ...