Search code examples
javascriptangularjsangular-filtersangular-translate

Apply Angular filter with an argument passed by another filter


I need to use the date filter with a format created by another filter. Trying to combine the date filter with the angular-translate filter.

With a hardcoded format I would have:

{{foo | date:'yyyy-MM-dd'}}

What I need is to get the date format by another filter.

Something like this:

{{foo | date:$filter('translate')('global.dateFormatNoTime')}}

or eventually this:

{{foo | date:('yyyy-MM-dd' | dateFormat)}}

'yyyy-MM-dd' being default format if the dateFormat filter not returning anything.

Right now I do this using a scope variable with the second filter applied on it in the controller.

{{foo | date:dateFormat}}

but wondering if can this be done directly in the view without another scope variable.


Solution

  • .filter('myCustomerFilter', function ($filter) {
        return function (date) {
            var dateFormat = $filter('translate')('global.dateFormatNoTime');
            return $filter('date')(date, dateFormat);
        }
    });
    

    And you can use this custom filter in your view.

    {{foo | myCustomerFilter}}
    

    Or if you want to pass the translate parameter into your filter you can define your custom filter like the below,

    .filter('myCustomerFilter', function ($filter) {
        return function (input, date, translateOption) {
            var dateFormat = $filter('translate')(translateOption);
            return $filter('date')(dateFormat);
        }
    });
    

    And in your view you can pass the translate parameter into your custom filter.

    {{foo | myCustomerFilter : 'global.dateFormatNoTime'}}