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

Can you explain the meanings of <div class="masthead pdng-stn1"> and <div class="phone-box wrap push" id="home"> in more detail?

While working on styling my web pages with CSS and Bootstrap, I came across a few classes like "masthead pdng-stn1" and "phone-box" in the code. Despite searching through the bootstrap.css file and all other CSS files in my folders, I couldn't find a ...

A guide to extracting attribute values from HTML using Angular 4

I am currently working on an Angular 4 project where I needed to implement drag and drop functionality. To achieve this, I utilized the ng2-dragula plugin. Now, I have a new requirement which involves extracting the data-id attribute from each row after it ...

Ways to automatically fill out form fields with information from a different webpage

I am working on an angularJS form similar to the one below <section> <form role="form" ng-if="authenticated != true" name="registerForm" ng-submit="register(registerForm)" novalidate> <input type="email" class="form-control" ng- ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Tips on using the .map() method to extract data from a JSON response received from a get request and utilizing the content within a specific index to populate table rows

Here is the JSON response representation, https://i.stack.imgur.com/0QWkv.png This is how my project displays it: https://i.stack.imgur.com/LnA5v.png The rendering code snippet is as follows: render() { const { materials } = this.state; ...

Updating the database table using javascript

I am looking to dynamically update my database based on a condition in JavaScript. Currently, I have been using the following approach: <a href="#" onclick="hello()">Update me</a> <script> function hello(smthing) { if(smthing == true) ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Custom React component - DataGrid

Just starting out in the world of React and attempting to create a custom component with parameters. I'm curious about the correct approach for achieving this. Here's my current code snippet - how do I properly pass Columns, ajax, and datasourc ...

Unlocking location data in React Router-DOM 6: A step-by-step guide

I am currently working on implementing a 'forgot password' feature, where I am attempting to transfer the email data from the 'login page' to the 'forgot password' page using a Link element. However, I am encountering an issu ...

Mapping two arrays in JavaScript involves iterating through each element of the arrays

I'm having trouble displaying the content of two arrays contained within an object. When I map over RType.information.Type, I can display the content of the "Type" array. However, I am unable to display both Type[] and Price[]. I've tried various ...

Is there a method to iterate through an HTML quiz in order to extract text from "label for" with the value of "true"?

I need assistance with extracting all the correct answers from a multiple choice radio button quiz. The correct answers are identified by the attribute value="true" in the HTML code. Is there a way to iterate through and retrieve the text of all the corr ...

Creating a Curved Border with Clip Path in CSS

Hey there! I'm currently attempting to add a speech bubble at the bottom left using clip-path, but I'm struggling to adjust the pixels just right to achieve the clear and exact look I want. Can someone provide suggestions on how to accomplish thi ...

The art of masonry is not effective

I'm having trouble getting the Masonry cascading grid layout library to work in my code. Stylesheet: .post { background: #FFF; padding: 10px; border-bottom: 3px solid #e6e6e6; width: 30.7%; margin: 10px; } Source code: <div ...

Is it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

Unable to access child props in parent event handler in React

Currently utilizing React for building a UI, the structure involves a parent component and a child component as shown below: // Child Component var ListItem = React.createClass({ render: function() { var link_details = ( <div> ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

The import 'react-router' does not include an export called 'browserHistory'. This issue is coming from the /src/App.js file

I've recently started diving into the routing section of learning react, but I'm a bit puzzled by the error message I encountered. Error: Failed to compile ./src/App.js 31:19-33 'react-router' does not contain an export named 'bro ...

Insects featuring a button and tooltip duo creating a captivating "pull-effect"

Why is the button pulling when I move the cursor over a camera? Is there a way to solve this issue? <div class="input-group-btn advanced-group"> <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Send Imag ...