简体   繁体   中英

Angularjs search product by price (from price to price)

I'm trying to add filter for searching the product by from price to price . I have following array in json format as $scope.products in the controller.

[
  {"product_id":"1","product_price":"185"},
  {"product_id":"2","product_price":"45"},
  {"product_id":"3","product_price":"123"},
  {"product_id":"4","product_price":"23"},
  {"product_id":"5","product_price":"776"}
]

And below is the loop in html

<ul class="items">
  <li ng-repeat="product in products | filter:{product_name: findname} | sizeFilter:(size_arr|filter:{on:true})" >
    <strong>{{product.product_name | CapsFirst}}</strong> 
    <strong>({{product.product_category}})</strong>
    <strong>({{product.product_size}})</strong>
    <strong>({{product.product_color}})</strong>
  </li>
</ul>

In the view I want to add two input fields for searching the products by price.

<input type="number" ng-model="from_price" /> 
<input type="number" ng-model="to_price" /> 

Can anyone guide me that I can develop in proper way. I've searched about it but couldn't found a tutorial, I'm not expertise in angularjs. Thank You...

Here's an example on plunkr of what you've been asking for. I have added a product name in order to distinguish them, try it.

https://plnkr.co/edit/NKos4x9eeB5dZQaypurg?p=preview

app.filter('sizeFilter', [function() {
    return function(values, config) {
      if (config.enabled) {
        var filterResult = [];
        angular.forEach(values, function(value) {
          if (value.product_price >= config.from_price && value.product_price <= config.to_price) {
            filterResult.push(value);
          };
        });
        return filterResult;
      }
      return values;
    }
}]);

In HTML

 <li ng-repeat="product in products |rangePrice:
{'toPrice':to_price,'fromPrice':from_price}">

In JavaScript

app.filter('rangePrice', function() {
    return function( items, rangePrice ) {
        var filteredValue= [];
        var toPrice= parseInt(rangePrice.toPrice);
        var fromPrice= parseInt(rangePrice.fromPrice);
        angular.forEach(items, function(item) {
            if( item.product_price>= toPrice&& item.product_price<= toPrice) {
                filteredValue.push(item);
            }
        });
        return filteredValue;
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM