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 = [];
  debugger;
  if (!salaryRange) {
   salaryRange = 4400;
  }
  for (i = 0; i < empAll.length; i++) {
   var emp = empAll[i];
   if (emp.salary >= salaryRange)
    filteredEmp.push(emp);
  }
  return filteredEmp;
 }
})


HTML part ng-repeat with model and filter
:

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

        </div>
    </div>
</div>
<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.

2 Comments

Previous Post Next Post