Custom Filter in AngularJS

In this tutorial, we are going to see how to create a custom filter for your specific requirements in AngularJS, how filters generally work in AngularJS and how to apply them on nested array . We are going to work on this in three stages –

  • Filtering on all Fields ie a generic filter
  • Filter by single field
  • Custom filter for specific requirements

Consider a json of a few people which we will use in this tutorial. Any object in that array of persons will look as shown below with person’s information and his friends list in nested array

[ {
    "index": 0,
    "name": "Kellie Warren",
    "gender": "female",
    "age": 22,
    "friends": [
      {
        "id": 0,
        "name": "Beverley Orr"
      },
      {
        "id": 1,
        "name": "Joanna Goodwin"
      },
      {
        "id": 2,
        "name": "Joyner Mcguire"
      }
    ]
  },
  {...}
  ]

We are showing the HTML in a table as

<input type="text" ng-model="searchText" />
<table>
    <tr>
        <th>S.No</th>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Friends</th>
    </tr>
    <tr ng-repeat="person in list | customFilter : searchText">
        <td>{{$index+1}}</td>
        <td>{{person.name}}</td>
        <td>{{person.age}}</td>
        <td>{{person.gender}}</td>
        <td>
            <ul>
                <li ng-repeat="friend in person.friends">{{friend.name}}</li>
            </ul>
        </td>
    </tr>
</table>

Filtering on all Fields

This is the most basic example of AngularJS filters where the search text entered by user is used to filter all the fields in the array. So if we enter “Kellie”, “female”, “22” or “Beverly”, we are going to get the object shown in the above array in the filtered results. filter : searchText is used inside ng-repeat to filter for this requirement.

Filtering by Single Field

If you want to filter, say, using only person names, then we can simple modify the angularJS filter a bit to accomodate that. In this case, we write filter : {name : searchText} : false for filtering. Moreever, if you want to filter using multiple fields with AND condition ie you want all persons with gender female AND age 22, you can simple write filter : {gender : genderSearchText, age: ageSearchText} : false. This takes the intersection of the two columns.

However, if you want to filter using multiple columns with OR condition (union) ie you want to apply filter on both person’s name as well as their friends’s names, and, if the any of the two matches the input text, you want to get it in the filtered list. For example, in the data shown above, if you want to get the object displayed on searching Kellie as well as her friend’s name Joanna, then you need to create a custom filter.

Custom Filter in AngularJS

Here, we are going to filter on the basis of persons’ names and their friends’ names.

Now, ng-repeat would look like ng-repeat="person in list | customFilter : searchText" where list is the array of persons, customFilter is the name of our customFilter and searchText is the text input by the user for searching.

Custom Filter

myApp.filter('customFilter', function() {
    return function(list, searchText){

        // If searchText is empty, return the whole list
        if(searchText==""){
            return list;
        }

        searchText = searchText.toLowerCase(); // Converting searchText to only lower case characters
        var filteredList = []; // Array to hold filtered list

        for(var i=0;i<list.length;i++){
            var person = list[i];
            var name = person.name.toLowerCase(); // Converting name to only lower case characters

            // If person's name has the substring searchText
            if(name.indexOf(searchText)!=-1){
                filteredList.push(person);
                continue;
            }

            // Checking friends names in similar way
            for(var j=0;j<person.friends.length;j++){
                var friend = person.friends[j]; 
                var friendName = friend.name.toLowerCase(); // Converting friend name to only lower case characters 
                if(friendName.indexOf(searchText)!=-1){
                    filteredList.push(person);
                    break;
                }
            }

        }
        console.log(filteredList);
        return filteredList;
    };
});

Here,

  • We first convert searchText and names to lowercase characters to nullify any impact of different character cases on filtering.
  • Second, we search if searchtext matches the name of the person. If it does, it is added to the filtered array.
  • Third, if the person’s name does not matches the searchText, we check if searchText matches or is substring of names of that person’s friends.
  • If nothing matches, then the object of the person is not added to the filtered array.

Result on searching Warren

Custom Filter

Please feel free to download the source code for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No