Anand Anand -4 years ago 103
AngularJS Question

Filter for number range : AngularJS

I have a form with some input types like text, radio etc. When I submit the form, it lists the entered details below the form(used template and directive for this). I want to do filter in age , ie, the number input type, such that when I give an age range, it should filter profiles with corresponding age range. Here is the plunker :

http://plnkr.co/edit/h8p8rtZuAhCoKClUjgE9?p=preview



<table border="1" style="width:200px">
<tr>
<td> <div>Name : {{ formElement.name }} </div><br> </td>
</tr>
<tr>
<td> <div>Age : {{ formElement.age }}</div><br> </td>
</tr>

Answer Source

You could write a custom filter function that filter by range on a particular field:

$scope.byRange = function (fieldName, minValue, maxValue) {
  if (minValue === undefined) minValue = Number.MIN_VALUE;
  if (maxValue === undefined) maxValue = Number.MAX_VALUE;

  return function predicateFunc(item) {
    return minValue <= item[fieldName] && item[fieldName] <= maxValue;
  };
};

and use it in ng-repeat expression:

<div ng-repeat="formElement in formElements | filter:byRange('age', filterModelMin.age, filterModelMax.age)">

Note that the filterModelMin.age and filterModelMax.age can be used directly in fasterDisplay directive because both fasterForm and fasterDisplay do not have their own scope.

Example plunker: http://plnkr.co/edit/dFbBCKxSxm9RI9dwSeYR?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download