Write Custom AngularJS Filter

Today, we will develop a moderately complex filter and learn about it in some level of detail.

The application


We will show a list of products. User can filter the list by minimum price and view only products that are on sale.

Build the basics

We will first build the basic application without any filter. It will show a list of all products.

Here is the code for the controller.

angular.module("SimpleModule", [])
    function($scope) {
      $scope.minPrice = 0;
      $scope.onSale = false;
      $scope.products = [
          name: "Baseball bat",
          onSale: true,
          price: 10.99
          name: "Baseball glove",
          onSale: true,
          price: 20.99
          name: "Golfing glove",
          onSale: false,
          price: 40.99

Now, the HTML:

<body ng-app="SimpleModule" ng-controller="MyCtrl">

<input type="number" ng-model="minPrice" placeholder="Minimum price"/>
<input type="checkbox" ng-model="onSale"/> On sale

<div ng-repeat="product in products">
        {{product.name}} {{product.price}}.


It is important to use input type number for the minimum price text field. This will preserve the data type of the minPrice variable as number.

Add the filter

Now, we will add a filter to the module. This filter will take in an array of all products and return a new array of products that match the search criteria.

.filter("productFilter", function() {
  return function(input, lowPrice, showSaleOnly) {
    lowPrice = lowPrice | 0;
    return input.filter(function(product) {
      return (product.price >= lowPrice) &&
        (showSaleOnly ? product.onSale : true);

Note that the filter takes two configuration parameters – lowest price and if only products on sale should be shown.

Actual filtering is being done by the Array.filter method which is supported by IE9 and up.

Let’s use the filter in HTML:

<div ng-repeat="product in products | productFilter:minPrice:onSale">
        {{product.name}} {{product.price}}.

Note that we are supplying the minPrice and onSale model variables as configuration parameters to the filter. As the user interacts with the input elements, these values will change and AngularJS will call the filter function to refresh the list.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.