Filters in controllers in AngularJS


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

A straightforward 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 approach to inject filter also to services and directives.

Following example injects a 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 the required filter inside the controller. The $filter component takes one string argument, 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 the second approach and reduce the number of dependencies / arguments in a controller function.

You can read more about AngularJS filters:


Tags:

#angularjs #controller #filter #javascript


You may also be interested in:



comments powered by Disqus