What is the proper way to utilize a date filter with ng-model in AngularJS?

I've been struggling with what seems to be a simple task - converting a date string to a date object and formatting it in Angular. Here's the issue:

In my Angular app and controller, I have the following code:

myApp.controller('myAppCtrl', function($scope) {
   $scope.MyDate = Date("2014-09-23T15:26:49.1513672Z");
})

The date I'm working with is returned from the server as a string in the format shown above.

I've looked at the Angular documentation on date filters

  <span>{{1288323623006 | date:'medium'}}</span><br>

and this outputs: Oct 28, 2010 8:40:23 PM

However, when I try to apply the same filter to $scope.MyDate like this:

  {{MyDate | date:'medium'}}

the date doesn't format correctly but looks like this: Wed Sep 24 2014 07:40:02 GMT-0700 (Pacific Daylight Time)

Ultimately, I want to bind an input text box to this value and format it using the same filter:

<input type="text" class="form-control" ng-model="MyDatee | date:'medium'"/>

If I can get the basic version working, I hope to solve my actual problem with the text input.

Here's a helpful plunker link with the above code

Answer №1

To start off, try utilizing new Date() instead:

$scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");

Next, consider developing a directive to format the model within the input (adapted from this source)

The structure looks like this:

<input type="text" class="form-control" ng-model="MyDate" formatted-date format="medium" />

And the directive is structured as follows:

angular.module('myApp').directive('formattedDate', function(dateFilter) {
  return {
    require: 'ngModel',
    scope: {
      format: "="
    },
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return dateFilter(data, scope.format); //converted
      });

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return dateFilter(data, scope.format); //converted
      });
    }
  }
});

Check out the revised plunkr

Answer №2

To update the MyDate variable in your $scope, you can use the following code:

$scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");

Answer №3

Check out this link for more information

However, it's not possible to use a filter inside an input to format the date. You can find more details on this issue here

 $scope.MyDate = new Date("2014-09-23T15:26:49.1513672Z");

Answer №4

To modify the date format, simply follow these steps:

<input type="text" class="form-control" value="{{MyDatee | date:'medium'}}"/>

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

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

"Combining the elegance of Jade with the power of Angular

Just the other day, I delved into the world of Jade and have prior experience working with AngularJS. During my exploration, I noticed a trend of people combining Jade with AngularJS. From what I gather, when utilizing AngularJS, we can leverage its feat ...

Unable to carry out specific tasks in a particular order with GULP

I'm having trouble getting the TASK cssmin to execute after scss. It works fine when the folder destination is not empty and .css files are already compiled with the 'scss' task, but if the folder is empty, the cssmin task doesn't creat ...

Can data be transferred between browsers, such as from Google Chrome to Mozilla Firefox?

I have a dilemma with two separate pages—one for Admin and the other for User. The Admin page is named index.html <!DOCTYPE html> <html lang="en"> <head> <style> * { padding: 0; ...

Express: Implementing Middleware Only on Specified Routes in a Router Object - A Comprehensive Guide

Looking to organize my routes by stacking router objects for better modularity. An issue arises when trying to add a middleware call exclusively to every route in a specific router without having to insert it into each route individually due to the size o ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Having trouble loading face-api.js models in Nextjs

Struggling to get the face-api.js models to load in a Nextjs app, I keep encountering this error: Unhandled Runtime Error Error: Failed to parse URL from /model/ssd_mobilenetv1_model-weights_manifest.json Oddly enough, this issue only occurs on Nextjs; t ...

What are the steps to implement session storage within a Puppeteer automation script?

Currently, I am attempting to retrieve the encounter id from a Puppeteer script that launches a browser. These scripts are executed on AWS synthetic canaries. However, when running the script, I encounter the following error: sessionStorage is not define ...

Rotating a div in HTML and CSS is not achieving the desired 180-degree rotation

Having trouble implementing a Fill animation that goes from the bottom to the top of the box .box-inner-1. The CSS Rotate property seems to be malfunctioning! $('.box-inner-1').css({ top: '0' }).animate({ "height": 260 }, 4000); ...

What is the best method for performing cross-domain queries utilizing ajax and jsonp?

When attempting to send an ajax request to a specific URL, I encountered an error. Below is the code I used: $.ajax({ url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n", dataType : 'jsonp', ...

Is it possible to trigger an ajaxcall once another one has finished executing?

Just curious, do you think the code snippet below is capable of triggering a second ajax function once the first one has completed successfully? if(xmlHttp) // xmlHttp represents an XMLHttpRequest object { xmlHttp.onreadystatechange = function() ...

Is there a standard event triggered upon the closing of a browser tab or window?

Does React have a built-in event that is triggered when a browser tab or window is closed? If it does, does it have support across different browsers? ...

Include the await keyword within the .then block

I'm trying to execute an await after receiving a response in the .then callback of my code: const info = new getInfo(this.fetchDetails); info .retrieve() .then((res) => { const details = this.getLatestInfo(res, 'John'); }) .ca ...

Tips for locating a particular row in Protractor

Can you explain how the solution discussed in this Stack Overflow thread works? I'm interested in understanding the specific logic behind selecting ID0001 in the code snippet provided below: element.all(by.repeater('item in $data track by $index ...

Can someone guide me on implementing Node.js clusters in my basic Express application?

— I have successfully developed a basic application that retrieves data (50 items) from a Redis DB and displays it on localhost. After running an ApacheBench test with parameters c = 100, n = 50000, I am achieving around 150 requests/sec on my aging dual ...

Having trouble with uploading multiple files through ajax

I have been struggling to figure out how to upload multiple files using AJAX and PHP. The documentation available is overwhelming, and I can't seem to get a clear understanding of the process. MY GOAL The main objective is to upload several files wi ...

Receiving a parseerror when trying to use AJAX to retrieve cross-domain data using WCF

While attempting to access a WCF Rest Service from Javascript using $.ajax, I encountered issues with cross-domain calls. Despite hours of research, I have made progress but am stuck on the final step. To begin, here is my client-side code: $.ajax({ ...

JavaScript program to split an array of strings into sets of arrays based on alphabetical order

I am looking to split an array of strings into multiple arrays based on alphabetical order. Can you help me achieve this? For example: let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana ...

AngularJS: The nested ng-repeat is iterated through multiple times, correlating with the length of the outer array

Can someone help me figure out why the ng-repeat is repeating more times than the length of the outer array? Here is the array in question: $scope.giornieventi = [{ Intestazione: "Questa settimana", Eventi: [{ Nome: "Giacomo", ...

An effective way to confirm a notify.js alert using selenium

I am trying to validate the text of a notification message with the following code structure: <div class="notifyjs-corner" style="top: 0px; left: 45%;"> <div class="notifyjs-wrapper notifyjs-hidable"> <div class="notifyjs-arrow" styl ...