AngularJS: How to Use Filter in Controller

In this article, I’m going to share about how to use filter in controller in Angular JS. It is common to see filter used in view but apparently I found that in some conditions we need to use filter in controller.

You have to know that in order to inject a filter, you need to use format yourFilterNameFilter.

1) Built-in Filter

AngularJS has built-in filter named filter that can be used to reduce array based on some condition. To use it, we have to inject it as filterFilter. Using this filter, you can specify condition by attributes or by text like example below.

script.js

(function(angular) {
  'use strict';
angular.module('appModule', [])
  .controller('appController', ['$scope', 'filterFilter', function($scope, filterFilter) {
    
    $scope.names = [
      {name: 'Tobias', gender: 'm'},
      {name: 'Jeff', gender: 'm'},
      {name: 'Lisa', gender: 'f'},
      {name: 'Diana', gender: 'f'},
      {name: 'James', gender: 'm'},
      {name: 'Brad', gender: 'm'}
    ];
    
    $scope.filteredNames = filterFilter($scope.names, 'a'); // by text, it will check inside name and gender
    $scope.filteredNamesByFemale = filterFilter($scope.names, {gender: 'f'}); // by attribute
  
  }]);
})(window.angular);

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>filterFilter - Budi Irawan</title>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
  <script src="script.js"></script>
  
</head>
<body ng-app="appModule">
  <div ng-controller="appController">
  <div>
    <strong>All names:</strong>
    <span ng-repeat="entry in names">{{entry.name}} </span>
  </div>
  <div>
    <strong>Names that contain an "a":</strong>
    <span ng-repeat="entry in filteredNames">{{entry.name}} </span>
  </div>
  <div>
    <strong>Names that gender is female:</strong>
    <span ng-repeat="entry in filteredNamesByFemale">{{entry.name}} </span>
  </div>
</div>
</body>
</html>

The result will be

All names: Tobias Jeff Lisa Diana James Brad
Names that contain an "a": Tobias Lisa Diana James Brad
Names that gender is female: Lisa Diana

Edit in Plunker

2) Custom Filter

We also can use our own filter to be called inside controller. It is almost same like above by injecting the filter name yourFilterNameFilter but I want to show you the alternative way with built-in $filter. Let’s we create simple filter named hello.

filter.js

(function(angular) {

'use strict';

angular.module('appModule')
  .filter('hello', function() {
    return function(input) {
      return 'hello ' + input;
    }
  });

})(window.angular);  

Then, in this controller, you can see the example for both of them. The result later will be same. However, I prefer use $filter if my controller use more than one filter.

script.js

(function(angular) {

'use strict';

angular.module('appModule', [])
  .controller('appController', ['$scope', '$filter', 'helloFilter', function($scope, $filter, helloFilter) {
    
    $scope.name1 = $filter('hello')('budi');
    $scope.name2 = helloFilter('sinta');
  
  }]);
  
})(window.angular);

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom Filter - Budi Irawan</title>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
  <script src="script.js"></script>
  <script src="filter.js"></script>
  
</head>
<body ng-app="appModule">
  <div ng-controller="appController">
  <div>
    <strong>{{name1}}</strong><br />
    <strong>{{name2}}</strong>
  </div>
</div>
</body>
</html>

The result will be

hello budi
hello sinta

Edit in Plunker

Summary

In this article, we learn about how to use filter in controller. AngularJS has a built-in filter named filter and we also can use our own filter in controller.

  • Dans le code Javascript
    Bien que ce cas d’utilisation soit plus rare, surtout quand on débute avec AngularJS, on peut tout à fait employer les filtres directement dans le code Javascript.
    En reprenant les éléments vus plus haut, la syntaxe est la suivante (rien de sorcier) :
    var donneesFiltrees = filtre(donnees, param1, param2);
    donneesFiltrees
    Comme on est cette fois au sein d’un code, il s’agit de récupérer la valeur retournée par notre filtre pour pouvoir s’en servir par la suite.

    Simplement, pour pouvoir utiliser un filtre, il faut bien sûr se placer dans un module AngularJS, que ce soit dans un contrôleur, une directive ou autre afin que le système d’injection de dépendances (Relire le paragraphe sur la Dependency Injection) puisse justement appeler le filtre demandé. Il y a alors 2 façons différentes de procéder :
    Avec le service $filter
    En intégrant le service $filter dans les dépendances du module concerné, on peut ensuite utiliser n’importe quel filtre :
    var demo = angular.module(‘demo’, [])
    .controller(‘demoCtrl’, [‘$scope’, ‘$filter’,
    function($scope, $filter){

    // définition du tableau ‘voitures’
    $scope.voitures = [
    {marque: ‘Renault’ , prix: 10000},
    {marque: ‘Peugeot’ , prix: 15000},
    {marque: ‘Citroen’ , prix: 20000},
    {marque: ‘BMW’ , prix: 35000},
    {marque: ‘Volvo’ , prix: 30000}
    ];

    // Récupération du filtre ‘orderBy’
    var orderBy = $filter(‘orderBy’);

    // utilisation du filtre ‘orderBy’
    $scope.voituresTrieesParMarque = orderBy(voitures, marque);
    }
    ]);

    Visit my site: http://serrurier-paris-urgent.com/

    En appelant directement le filtre concerné
    Pour signaler qu’un module a besoin d’un filtre précis, on peut l’ajouter dans les dépendances mais en ajoutant au nom du filtre le suffixe Filter :
    var demo = angular.module(‘demo’, [])
    .controller(‘demoCtrl’, [‘$scope’, ‘orderByFilter’,
    function($scope, orderByFilter){

    // définition du tableau ‘voitures’
    $scope.voitures = [
    {marque: ‘Renault’ , prix: 10000},
    {marque: ‘Peugeot’ , prix: 15000},
    {marque: ‘Citroen’ , prix: 20000},
    {marque: ‘BMW’ , prix: 35000},
    {marque: ‘Volvo’ , prix: 30000}
    ];

    // utilisation du filtre ‘orderBy’
    $scope.voituresTrieesParMarque = orderByFilter(voitures, marque);
    }
    ]);