Oct 20, 2017

Textual description of firstImageUrl

Custom filter in Angular : How to write a custom filter in AngularJS

Angular provides filtering capability which can be converting string from lower case to uppercase, converting time to Date or Sort(increasing or decreasing) an array based on some attributes. In this post we will see how to write custom filter - Filtering array elements based on some condition and show filtered elements in view.

Suppose we have an Employee model which contains name, salary, Address and phone. We have a grid showing all the fields in UI. We want to write a filter in Angular which shows employees with salary greater than input value in text field.

Data model:

    name : "Nikhil",
    address : "Hyderabad",
    Phone : "9988776655",
    salary : 3500,
    imgUrl : "img/1.ico"

We are writing filter below based on salary, if input is passed filter will use it else it will use default value as 4400 hardcoded inside filter function. This filter return a function which internally prepare a filtered array.

Filter Script: 

 * custom filter returing a function,if salary is not passed default value 4400
 * is used.
app.filter('salaryFilter', function() {
 return function(empAll, salaryRange) {
  var filteredEmp = [];
  if (!salaryRange) {
   salaryRange = 4400;
  for (i = 0; i < empAll.length; i++) {
   var emp = empAll[i];
   if (emp.salary >= salaryRange)
  return filteredEmp;

HTML part ng-repeat with model and filter

    ng-repeat-start="emp in employeeArray.myarr|salaryFilter:inputVal.salary"
    layout-align="left center" layout-padding>
    <div class="productImgAndText">
        <div class="orderDetailsText">
                <img ng-src="{{emp.imgUrl}}" width="60px">
                <h5>Address and Phone</h5>
                <p ng-class="{blueText : $index == 1}">{{emp.salary}}</p>

<hr ng-repeat-end />

Here inputVal.salary in filter is bind with input text from where we pass salary based on which filter computes and prepare filtered array.

Below is screenshot attached with input and filtered output.

Download complete source code.
Location: Bengaluru, Karnataka, India