javascript - AngularJS filter with integer comparison - Stack Overflow

admin2025-04-19  0

so I have a "price" field on my site made using JQuery-UI slider. This field consists of 2 integer values: minPrice, and maxPrice.

Assume I have an array of objects that looks like this:

objarr=[
 {
  'name'='item1',
  'price'=100
 },
 {
  'name'='item2',
  'price'=200
 },...
]

and also the following div with ng-repeat:

<div ng-repeat="obj in objarr">
  {{obj.name}}: ${{obj.price}}
</div>

How do I create a filter such that only objets with obj['price'] > minPrice and obj['price'] < maxPrice will show?

so I have a "price" field on my site made using JQuery-UI slider. This field consists of 2 integer values: minPrice, and maxPrice.

Assume I have an array of objects that looks like this:

objarr=[
 {
  'name'='item1',
  'price'=100
 },
 {
  'name'='item2',
  'price'=200
 },...
]

and also the following div with ng-repeat:

<div ng-repeat="obj in objarr">
  {{obj.name}}: ${{obj.price}}
</div>

How do I create a filter such that only objets with obj['price'] > minPrice and obj['price'] < maxPrice will show?

Share Improve this question asked Sep 25, 2014 at 8:06 DisbobulousDisbobulous 1,1843 gold badges15 silver badges27 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You can write a simple helper function in controller:

$scope.filterRange = function(obj) {
    return obj.price > $scope.range.minPrice && obj.price <= $scope.range.maxPrice;
};

and use it in HTML:

<div ng-repeat="obj in objarr | filter:filterRange">
    {{obj.name}}: ${{obj.price}}
</div>

Demo: http://plnkr.co/edit/uoynjdSI1ajrm02qp3v8?p=preview

Another way is to write an Angular filter

app.filter('pricebetween', function(){
  return function(items, min, max) {
      var filtered = [];
      angular.forEach(items, function(item, key) {
          if(item.price <= max && item.price >= min) { 
              filtered.push(item);
          }
      });
      return filtered;
  };
});

And then in the code

<div ng-repeat="obj in list | pricebetween:300:500">

In plnkr example I also have greater than filter.

http://plnkr.co/edit/f0hJpwK4TrwdgJvPRZRo

you can use ng-show filter :) , it is very easy and fits in your question , use it like that , span> {{obj.name}}: ${{obj.price}} span> docs for ng-show: https://docs.angularjs/api/ng/directive/ngShow

Best Wishes :)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745075544a283545.html

最新回复(0)