3

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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

When I tried this method, it didn't work because the value for $scope.range was set after the objects have loaded. Also the filter didn't get updated after the values for $scope.range changed.
In both cases you probably don't trigger $digest loop.
simple solution, superb :)
1

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

Comments

0

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.org/api/ng/directive/ngShow

Best Wishes :)

1 Comment

it is so , but in case of large number of datas in use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.