Skip to content

Custom filters in AngularJS

Last updated on April 22, 2016

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 –

  
Name
{{user | fullNameFilter}}

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments