Posted by Arjun on Friday 5th December 2014

Custom filters in AngularJS

Intermediate Angular Js Anguarl Js Filter

This tutorial will show you, creating your own custom filters in AngularJS with simple steps and example. Angular filters provides a way to format the variable output without changing scope variable. Whenever possible use filters to keep presentation logic out of the controllers.

Angular providing a .filter() method for each module. We can write your own custom filters by using .filter() method. Let's look at the skeleton of angular filter.

angular.module('',[]).filter('', function () {
  return function () {
    return;
  };
});

Here you can find that we are defined our module and called filter() method. Here first parameter is your filter name and second one is your callback. This callback will return the function, returned function gets invoked each time whenever Angular calls the filter, which means two-way binding is happening.

AngularJS Custom Filter Example

I am gonna create full name filter.

angular.module('customFilters',[]).filter('fullName', function () {
  return function (input) {
    return input.first_name+' '+input.last_name;
  };
});

How to use full name filter

Let's create a app module called "user", which is dependent on "customFilters" module, so lets import it by mentioning it the decencies list it of user module, as shown below.

 angular.module('user',['myFilters']);
 function userController($scope,$http) {
    $scope.users = [{"first_name":"Arjun","last_name":"PHP"},{"first_name":"Pravinh","last_name":"PHP"}];
 }

Lets see the output by using it in the HTML -

  <div ng-app="arjun">
      <table ng-controller="userController" class="table table-bordered table-condensed table-responsive">
      <thead>
        <tr>
          <td>Name</td>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="user in users">
          <td>{{user | fullNameFilter}}</td>
        </tr>
      </tbody>
    </table>
  </div>

congratulations! Your first filter is ready.

Passing arguments to the filters

In templates, you can pass and separate filter arguments by colons.

Syntax:

{{ yourExpression | yourFilter: arg1:arg2:... }}

Example:

angular.module('myFilters',[]).filter('fullName', function () {
  return function (input,n1,n2,n3..nn) {
    // your logic
  };
});

That's it.