Search code examples
angularjsangularjs-directiveangularjs-service

How to declare directive or service i can use like a function in AngularJS expression


I have many functions to convert Datetime format. I'd like to create a directive or a service to call these functions everywhere in my project.

Here is one of my functions.

$scope.formatDateTime = function (item) {
    if (item != null) {

        var d = moment().utc();
        if (item instanceof Date)
            d = new moment(item).utc();

        else if (item instanceof moment)
            d = item;

        else
            d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();

        if (d != null) {

            moment.locale($rootScope.language);
            var strReturn = d.format("L LT");
            return strReturn;
        }
    }

    return null;
};

My problem is i have to copy my functions in every controller where i need to use them, so i'd like to call a service or directive, i don't really know what exactly, to call these functions like below :

<div>{{formatDateTime(dateToConvert)}}</div>

Solution

  • best solution is to create a custom filter

    .filter('dateFilter', function() {
        return function(item) {
            if (item != null) {
                var d = moment().utc();
                if (item instanceof Date)
                    d = new moment(item).utc();
                else if (item instanceof moment)
                    d = item;
                else
                    d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();
                if (d != null) {
                    moment.locale($rootScope.language);
                    var strReturn = d.format("L LT");
                    return strReturn;
                }
            }
            return null;
        }
    })
    

    in the html, call like this

    <div>{{dateToConvert | dateFilter}}</div>