-1

I want to filter results by id, or rating and various other keys, I'm using this data structure:

[
{
    "id": "1"
    "Description": "desc 1",
    "Rating": "rating 1",
    "MainImage": "image.jpg"
},
{
    "id":"1"
    "Description": "desc 2",
    "Rating": "rating 2",
    "MainImage": "image.jpg"
},
{
    "id": "2"
    "Description": "desc 3",
    "Rating": "rating 3",
    "MainImage": "image.jpg"
}
]

This data is returned from a promise and is assigned to $scope.results. In the template there is an ng-repeat to iterate over the results. This is working fine, my question is:

How do I filter the results by id so for example only the results with the id of 1 are displayed? I had this working but it wasn't the most efficient. I reassigned the filtered results back to $scope.results which did work but then the entire data structure had been replaced by the one containing the filtered results. That obviously wasn't going to work and I did a work around but I know this isn't the best way.

I need a custom filter that will be able to handle filtering using 3 different select lists so for example a rating select list, a productId and a productName.

How exactly would I write this function?

<div class="product" data-ng-repeat="product in products | filter:searchFilter"></div>
user1532669
  • 2,288
  • 4
  • 36
  • 72
  • 1
    Off topic: ID values should be unique, regardless of their application. – isherwood Dec 02 '14 at 20:06
  • 2
    possible duplicate of [How to filter by object property in angularJS](http://stackoverflow.com/questions/17793751/how-to-filter-by-object-property-in-angularjs) – isherwood Dec 02 '14 at 20:07
  • see [http://stackoverflow.com/questions/26874748/how-to-render-only-visible-items-in-angularjs-dropdown/26874894#26874894](http://stackoverflow.com/questions/26874748/how-to-render-only-visible-items-in-angularjs-dropdown/26874894#26874894) – letiagoalves Dec 03 '14 at 21:01

3 Answers3

0

I ended up doing something that I found here and created a function in the backend. Something like:

$scope.searchFilter = function (item) {
    return (item.id === $scope.results.id)
}

This code isn't exactly what I've used but that's the general idea. Seems to work :)

Community
  • 1
  • 1
user1532669
  • 2,288
  • 4
  • 36
  • 72
0
//This will filter the product list based on all 3 criteria
<div class="product" data-ng-repeat="product in products | filter:{rating:selectedRating, id:selectedId,productName:selectedProduct }"></div>
-1

This is how I do it.

<input type="number" ng-modal="idFilter:selectedID">
<div ng-repeat="result in results | idFilter:selectedID | track by $index">
<something-repeated>
</div>

<script>
 angular.module('whatever').filter('idFilter', function(){
  return function(results, selectedID){
    return results.filter(function(result){
      return result.id == selectedID;
    });
  }
});
</script>
UnbrandedTech
  • 461
  • 6
  • 14