6

I want to use multiple filters in controller

Currently using

$filter('limitTo')($filter('lowercase')($filter('translate')('ACTIVE')), 5)

If we have more filters like this. How can I use multiple filters in controller rather conventional format like this?

3
  • What's your question exactly? The question has the answer: you're already using multiple filters in the controller. Commented May 22, 2015 at 6:35
  • 1
    I am using multiple filters @JB Nizet. Simplified format I want than this. Commented May 22, 2015 at 6:54
  • similar to: stackoverflow.com/questions/27852445/… Commented May 22, 2015 at 7:09

2 Answers 2

3

You can simply introduce variables:

var limitTo = $filter('limitTo');
var lowercase = $filter('lowercase');
var translate = $filter('translate');

var filteredValue = limitTo(lowercase(translate('ACTIVE')), 5);

Or even

var lowercaseStatus = lowercase(translate('ACTIVE'));
var filteredValue = limitTo(lowercaseStatus, 5);

Another strategy would be to use the same syntax as in the view:

var filteredValue = $scope.$eval('"ACTIVE" | translate | lowercase | limitTo:5');
Sign up to request clarification or add additional context in comments.

Comments

1

This is an interesting question. Usually you would do something like that or something like this:

var translatedValue = $filter('translate')('ACTIVE');
var lowercaseValue = $filter('lowercase')(translatedValue);
$scope.finalValue = $filter('limitTo')(lowercaseValue, 5)

I created a service inspired by this answer.

app.service('FilterChain', 
['$filter', function($filter) {
    var chain = {
        value : '',
        start : function(value) {
            this.value = value;
            return this;
        },
        applyFilter : function(filterName, args) {
            args = args || [];
            args.unshift(this.value);
            this.value = $filter(filterName).apply(undefined, args)
            return this;
        }
    };

    return chain;
}]);

Usage is like this

$scope.value = FilterChain.start('Active')
                .applyFilter('translate')
                .applyFilter('limitTo', [5])
                .applyFilter('uppercase')
                .value;

You can use the service with other filters and objects such as arrays. See a working example here: JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.