How to use angularjs filters

What Is AngularJs Filter ?

Selects a subset of items from array and returns it as a new array.

A filter is very similar to a factory or service in many regards. But it has the added advantage of behaving on a global scope once created. As we have previously seen, you can invoke a filter on both the data binding in your HTML or directly inside of your controller or directive.

Basic usage of AngularJs Filters

In HTML Template Binding

[[ filter_expression | filter : expression : comparator ]] <!-- AngularJs Print Symbols are Interpolated to '[[', ']]'-->

In JavaScript

$filter('filter')(array, expression, comparator)

AngularJs Custom Filter

As you know, AngularJs lets us to create custom filters and use it like you use other filters.To do that, you can use filter(...) function to create filter inside you module.Let's see the syntax how we can create custom filter.

angular.module('MyModule').filter('myFilter', function() {
  return function(input, arg1, arg2) {
    var output;
    // code ...
    return output;
  }
});

You can use this filter inside your controller, directive, etc.. or inside you template with the syntax we gave you. Now we are going to create a filter (demo), which lets you filter by gender of the user's list.

<!DOCTYPE html>
<html>
  <head>
    <title>www.W3docs.com</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
  </head>
  <body data-ng-app="MyModule" data-ng-controller="MyController">
    <select data-ng-model="filterGender">
      <option value='male'>Male</option>
      <option value='female'>Female</option>
    </select>

    <ul>
      <li data-ng-repeat="user in users | gender:filterGender" data-ng-bind="user.name"></li>
    </ul>

    <script>
      angular.module('MyModule', [])
       .controller('MyController', function($scope){
         $scope.users = [
            {name: 'Mike', gender: 'male', age: 23},
            {name: 'Jenifer', gender: 'female', age: 32},
            {name: 'Tom', gender: 'male',  age: 14},
            {name: 'Hayk', gender: 'male', age: 18},
            {name: 'Eliana', gender: 'female', age: 28}
         ];
       })
       .filter('gender', function(){
         return function(users, gender){
           if(!gender){
             return users;
           }
           var arr = [];
           angular.forEach(users, function(v){
             if(v.gender === gender){
               arr.push(v);
             }
           })

           return arr;
         }
       })
    </script>
  </body>
</html>

Do you find this helpful?

Related articles