How to use a filter in a controller? How to use a filter in a controller? angularjs angularjs

How to use a filter in a controller?


Inject $filter to your controller

function myCtrl($scope, $filter){}

Then wherever you want to use that filter, just use it like this:

$filter('filtername');

If you want to pass arguments to that filter, do it using separate parentheses:

function myCtrl($scope, $filter){    $filter('filtername')(arg1,arg2);}

Where arg1 is the array you want to filter on and arg2 is the object used to filter.


Answer provided by @Prashanth is correct, but there is even easier way of doing the same. Basically instead of injecting the $filter dependency and using awkward syntax of invoking it ($filter('filtername')(arg1,arg2);) one can inject dependency being: filter name plus the Filter suffix.

Taking example from the question one could write:

function myCtrl($scope, filter1Filter) {   filter1Filter(input, arg1);}

It should be noted that you must append Filter to the filter name, no matter what naming convention you're using:foo is referenced by calling fooFilter
fooFilter is referenced by calling fooFilterFilter


Using following sample code we can filter array in angular controller by name. this is based on following description.http://docs.angularjs.org/guide/filter

this.filteredArray = filterFilter(this.array, {name:'Igor'});

JS:

 angular.module('FilterInControllerModule', []).    controller('FilterController', ['filterFilter', function(filterFilter) {      this.array = [        {name: 'Tobias'},        {name: 'Jeff'},        {name: 'Brian'},        {name: 'Igor'},        {name: 'James'},        {name: 'Brad'}      ];      this.filteredArray = filterFilter(this.array, {name:'Igor'});    }]);

HTML

<!doctype html><html lang="en"><head>  <meta charset="UTF-8">  <title>Example - example-example96-production</title>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>  <script src="script.js"></script>    </head><body ng-app="FilterInControllerModule">    <div ng-controller="FilterController as ctrl">    <div>      All entries:      <span ng-repeat="entry in ctrl.array">{{entry.name}} </span>    </div>    <div>      Filter By Name in angular controller      <span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>    </div>  </div></body></html>