Set an AngularJS date filter format to be used by all references to the date filter?

Kabb5 picture Kabb5 · Aug 22, 2013 · Viewed 27.7k times · Source

Rather that having to define a custom format for each call to the date filter, is there a way to globally define a default format (other than 'medium')?

I would like to have the format set in one file rather than all over the place in my code (the date format may end up being changed in the future and a modification in one file would be much nicer than having to make changes in many files).

This is what I am doing now (defining date format each time):

{{systemTime | date:'dd MMMM @ HH:mm:ss'}}
{{modifiedTime | date:'dd MMMM @ HH:mm:ss'}}
{{getShippedTime() | date:'dd MMMM @ HH:mm:ss'}}
   etc.

I was thinking of creating a custom filter (let's call it myDate), which would act as a wrapper and then pass off the date string to the Angular date filter with my custom format, so then my code could just look like this:

{{systemTime | myDate}}
{{modifiedTime | myDate}}
{{getShippedTime() | myDate}}
   etc.

However, I can't figure out how to make the myDate filter point to the Angular date filter.

Thanks for your help.

Answer

Kabb5 picture Kabb5 · Aug 23, 2013

Based on some more research and then considering the comment by moderndegree, I have found that the following myDate filter will work:

.filter('myDate', function($filter) {    
    var angularDateFilter = $filter('date');
    return function(theDate) {
       return angularDateFilter(theDate, 'dd MMMM @ HH:mm:ss');
    }
});