adilapapaya adilapapaya - 6 months ago 8
AngularJS Question

Angular js (1.5) date filter: making it modular

I have this sprinkled in various different templates in my app.

<span>
{{value.date | date : "yyyy-MM-dd HH:mm" : 'PDT'}} PDT
</span


I'll always use the same date format throughout the app.

I'm trying to figure out how to modularize the above so that I'm not repeating the same thing everywhere. I think the right way to do this is to make a component and then just use that wherever I need. E.g.

<formatted-date value="value"></formatted-date>


but I'm not sure if that is the correct way or if I should use a service/controller instead...?

The docs mention using

$filter('date')(date, format, timezone)


but I'm a bit lost as to where that would go in the general scheme of things (service/controller?).

(Apologies in advance if this is a stupid simple question or if I'm using the wrong terminology...I'm new to Angular and still trying to figure out the right way to do things.)

Answer

Have you thought about creating a custom filter? You could then replace all instances with:

{{value.date | myDateFormat}}

Heres an example:

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

    return function (input) {

        if (input) { 

            // set your dateFormat and timezone here
            var dateFormat = "yyyy-MM-dd HH:mm";
            var timezone = "PDT";

            // format your date
            var formattedDate = $filter('date')(new Date(input), dateFormat,  timezone);

            return formattedDate;

        };

        return "";

    };

}]);

This will enable you to use the same date format and easily change it in the future.

Otherwise, If you are looking to always keep the span tags and PDT text too, then yes, create a component that you can re-use where you need it. You can achieve this by using a directive.

You can provide a template and pass in the $filter service to your directive and do the same logic there.