Why Custom Filters?

Filters in AngularJS are mainly used for display purposes – to show a text in a specific way or to filter an array based on a certain pattern. We’ll see examples for both cases.

Single value display filter

Let’s assume that I need to display a date in a certain way: “Jack started working at …”. To do that I’m going to create a custom filter:

	app.filter('dateViewer', function() {
	      return function(input) {
	         var d = new Date(input);
	         return "Jack started working at "+d.toDateString();
	      };
	});   

To use that filter in the HTML all I have to do is to apply the filter on any date object:

	{{date | dateViewer}

When rendering the page the user will see:

Jack started working at Tue Feb 03 2015

If I wanted to use that filter for any user, I need to make the user name a parameter that I can pass to the filter. I can do that by passing the name in the HTML:

	{{date | dateViewer:’Bob’}}

And capturing that name in the function:

	app.filter('dateViewer', function() {
	   return function(input,name) {
	          var d = new Date(input);
	          return name+" started working at "+d.toDateString();
	   };
	});

Of course ‘Bob’ can be a variable:

	{{date | dateViewer: userName}}

and with that I got the filter to work dynamically for any name.

Notice that what we did was just passing the parameter and capturing it. That applies for as many parameters as we want:

	{{date | dateViewer: username: profession: ….}}
	return function(input,name,profession,….)

Filtering an array

Let’s assume that I have this array:

	$scope.users = ["Scott","Jack","Bob"];

By using ng-repeat to loop through the array:

	<div ng-repeat = "user in users">
	     {{user}}
	</div>

The result will be:

Scott
Jack
Bob

Now I want to show only the users that have the letter “a” in their names. For that I’m going to create a custom filter:

	app.filter('arrayFilter', function() {
	    return function(users) {
	        var filteredUsers = [];
	        for (var i = 0; i < users.length; i++){
	            if (users[i].indexOf("a")>-1){
                        filteredUsers.push(users[i]);
                    }
	        }
	        return filteredUsers;
	    };
	});

When applying that filter to the array:

	<div ng-repeat = "user in users | arrayFilter">
	     {{user}}
	</div>

The result will be:

Jack

Let’s expand this example a little bit. I’m sure when surfing the Internet you’ve seen pages that have input box and a list that filters immediately based on your input. It’s a very cool feature that can easily be done in AngularJS.

First we need to change our previous HTML piece to be:

	<input type="text" ng-model="chars">
	<div ng-repeat = “user in users | arrayFilter : chars”>
	     {{user}}
	</div>

Then we need to capture that parameter in the filter function:

	app.filter('arrayFilter', function() {
	    return function(users,chars) {
	        var filteredUsers = [];
                for (var i = 0; i < users.length; i++){
                    if (users[i].indexOf(chars)>-1){
                        filteredUsers.push(users[i]);
                    }
                }
                return filteredUsers;
	    };
	});

At the beginning AngularJS will show the whole list for you (make sure to initialize $scope.chars = “” in the controller; otherwise the list will show up empty at the beginning). If we entered “o” in the input box, the list shows:

Scott
Bob

If you continued typing “ob” the list will show:

Bob

As you can see, AngularJS filters are very powerful, and can give your site or mobile application a smooth user experience that separates average from awesome!

Share This