AngularJS : ng-repeat filter when value is greater than

Oam Psy picture Oam Psy · Jun 6, 2014 · Viewed 66.7k times · Source

I have a simple ng-repeat that throws out data, one of fields it displays is NumberOfStamps:

<tr ng-repeat-start="list in Data.Items ">
   <td><a href=" {[{list.Title}]} {[{list.ForeName}]} {[{list.SurName}]}</a></td>
   <td>(Date of Birth {[{list.Dob}]})</td>
   <td>{[{list.NumberOfStamps}]}  stamps</td>
</tr>

Example output:

Mr Adam Happy  Date of Birth 01/6/1984     16 stamps
Mr Adam Sad    Date of Birth 24/11/1975    0 stamps
Mr Adam Green  Date of Birth 02/1/1963     1 stamps
Mr Adam Red    Date of Birth 21/1/1951     12 stamps
Mr Adam Blue   Date of Birth 28/10/1998    0 stamps
Mr Adam Brown  Date of Birth 25/9/2010     0 stamps
Mr Adam Black  Date of Birth 24/8/1954     21 stamps
Mr Adam Violet Date of Birth 17/5/1942     54 stamps

How can i modify this ng-repeat to only show records where the NumberOfStams is > 0? I've tried:

<tr ng-repeat-start="list in Data.Items | filter:{NumberOfStamps > 0}">
   <td><a href=" {[{list.Title}]} {[{list.ForeName}]} {[{list.SurName}]}</a></td>
   <td>(Date of Birth {[{list.Dob}]})</td>
   <td>{[{list.NumberOfStamps}]}  stamps</td>
</tr>

Expected output:

Mr Adam Happy  Date of Birth 01/6/1984     16 stamps
Mr Adam Green  Date of Birth 02/1/1963     1 stamps
Mr Adam Red    Date of Birth 21/1/1951     12 stamps
Mr Adam Black  Date of Birth 24/8/1954     21 stamps
Mr Adam Violet Date of Birth 17/5/1942     54 stamps

Answer

Marc Kline picture Marc Kline · Jun 6, 2014

Create a predicate function on the relevant scope:

$scope.greaterThan = function(prop, val){
    return function(item){
      return item[prop] > val;
    }
}

As a first argument, it takes a property name on the object. The second argument is an integer value.

Use it in your view like this:

<tr ng-repeat-start="list in Data.Items | filter: greaterThan('NumberOfStamps', 0)">

Demo