In this post, I am sharing how to use a filter in a controller in AngularJS.

Very easy way of injecting a filter is to inject dependency with the name composed of the filter name and the Filter suffix: <filterName>Filter. E.g. the dependency customFilter injects custom filter. The injected component is a filter function.

Note that you can use this approache to inject filter also to services and directives.

Following example injects filter called custom.

var module = angular.module('module', []);

module.controller('MyCtrl', ['$scope', 'customFilter',
    function ($scope, custom) {
        // The 'custom' filter gets two arguments: arg1 and arg2
        $scope.filteredValue = custom(arg1, arg2)
    }
]);

Another way is to inject $filter dependency to your controller and fetch required filter inside the controller. The $filter component takes one string arguments which is a name of the filter function to retrieve.

Following example fetches custom filter and calls it with two arguments arg1 and arg2.

var module = angular.module('module', []);

module.controller('MyCtrl', ['$scope', '$filter',
    function ($scope, $filter) {
        // Retrieve 'custom' filter and execute it with two arguments: arg1 and arg2
        $scope.filteredValue = $filter('custom')(arg1, arg2);
    }
]);

I personally prefer the first approach. However, in some cases, where you need to use more filters in a controller, you can use second approach and reduce number of dependencies / arguments in a controller function.

You can read more about AngularJS filters