Standardize date formatting in AngularJS

Retrieve the date in the shared format:

{{ dateValue | date:{{dateFormat}} }}

The following service is provided:

app.service('formatting', function() {
      var format = new Object();

      format.dateFormat = 'medium'

      var getDateFormat = function(){
          return format.dateFormat;
      };

      return {
        getDateFormat : getDateFormat
      };
    });

Is accessing the date format in this manner permissible?

How can the date format be centralized for use across multiple view pages?

Check out this fiddle I've been working on:

http://jsfiddle.net/DG24c/99/

fiddle src :

html : 
<div ng-app="myApp">
  <div ng-controller="farmController">
      <div>{{ cTime | dateFormat }}
    </div>
  </div>
</div>


javascript : 

var myApp = angular.module('myApp', []);

myApp.controller("farmController",function($scope){
    $scope.cTime = 1439396762286;   
})

myApp.service('formatting', function() {

      var getDateFormat = function(){
          return 'medium'
      };

      return {
        getDateFormat : getDateFormat
      };

    });


myApp.filter('dateFormat', function($filter, formatting) {

       return function(date) {
         return $filter['date'](date, formatting.getDateFormat())
       }

    })

Answer №1

You can easily create a new filter called myDateFormat that utilizes both your service and the dateFilter in AngularJS. Take a look at this example on how to use the date filter in various parts of your code: AngularJS - convert dates in controller

To implement this filter, simply add the following line wherever you want to apply it:

 {{ dateValue | myDateFormat }}

Here's how the filter function might look:

app.filter('myDateFormat', function($filter, formatting) {

   return function(date) {
     return $filter('date')(date, formatting.getDateFormat())
   }

})

If you'd like to see a working example, check out this JSFIDDLE link: http://jsfiddle.net/pwhnaxd7/

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

One way to enhance user experience is by passing parameters dynamically from the database when an element is clicked. This allows for the retrieval of

Earlier, I tried to post a question but couldn't get it working due to incorrect code. As the title suggests, my objective is to retrieve data from a database and display it in a div. The idea is that when this data is clicked, it should be passed to ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Designing personalized visualizations using elasticsearch

After setting up ELK tools, I have a desire to extract data from Elasticsearch and generate my own graphs without relying on Kibana. I've heard about tools like elasticsearch.js, but I'm unsure how to begin using it. What steps should I take in o ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

How can I access a specific variable from a div in ng-class?

In one of my projects, I am utilizing a div with three conditional ng-class attributes as shown below: <div name="type" ng-class="{'class-one' : stringVariable != "type", 'class-two': stringVariable == "type" && booleanTrue, ...

What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route. Oddly e ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

The functionality of ZoneAwarePromise has been modified within the Meteor framework

After updating to the latest Angular 2.0.1 release on Meteor 1.4.1.1, I'm facing an error that says: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten I've attempted running meteor update and meteor reset, b ...

Exploring the usage of the Date method in React

When I insert the given code snippet import React,{Component} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Date extends React.Component{ dataToString = (d) =>{ ...

Creating a Custom Error Page in SpringBoot

After developing an application with SpringBoot that features webservices and a front-office coded in ReactJs, the default port was set to 8080. To simplify the URL access, I decided to switch this application to port 80 by adding the code snippet below to ...

The command "npm run build" is not running successfully, likely due to npm not being able to interpret ES6 syntax

I am currently developing a web application using Vue.js and Flask. While I can successfully compile the Vue app on my laptop by running npm run build and integrating the static files into my Flask app, I encounter an issue when attempting to do this on a ...

Is it possible to trigger a Bootstrap 5.2 Popover within an "if" statement?

As part of my input validation process, I am utilizing popovers. However, I am struggling with the syntax to make it work as intended. https://jsbin.com/sufitelodo/1/edit?html,js,output The JSBin provided serves as the foundation for this issue. I am un ...

Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...

Clear the Chrome Console of two warnings by resolving them in AngularJS

I'm getting ready to send out a Release Candidate of my Angular Application, but I'm having trouble resolving two warnings that keep popping up in the Chrome console. Here are the warnings: 'Attr.textContent' is deprecated. Please use ...

What is the best way to showcase the following values using Vue.js?

{"status":true,"data":[{"ref_id":"22","agent_id":"68","p_id":"84","description":"i am interested"},{"ref_id":"24","agent_id":"68","p_id":"84","description":"For more information about Bootstrap and Bootstrap Glyphicons, visit our Bootstrap Tutorial.For mor ...

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...