leaksterrr
leaksterrr

Reputation: 4166

Angular filter by categories in array

I have a products JSON file and each product within the JSON file has it's own set of tags (some of which are shared across other products!). Is it possible for me to use ng-repeat to create a list of tags found in the array and then be able to click on these generated tags to then filter the items on the page by the clicked tag? Each attribute should only appear once in the list, there should be no repeated attributes. Is this possible or will the filter have to be hard-coded? I'm still pretty new to Angular so unsure of it's limitations.

Upvotes: 0

Views: 118

Answers (1)

Jerrad
Jerrad

Reputation: 5290

Create a function to loop through all your attributes in all your products, adding the attribute to an array if it doesn't already exist.

$scope.getAttributes = function(){
  var attributes = [];
  angular.forEach($scope.data, function(item){
    angular.forEach(item.attributes, function(attribute){
      if(attributes.indexOf(attribute) == -1)
        attributes.push(attribute);
    })
  })
  return attributes;
}

Now you can create a list of tags in HTML for those attributes:

<div ng-repeat="a in getAttributes()" ng-click="setFilter(a)">{{a}}</div>

Clicking an attribute will set a selectedAttribute variable, which is used to filter the product list:

<table>
    <tdata>
      <tr ng-repeat="d in data | filter:{attributes: selectedAttribute}">
        <td>{{d.name}}</td>
        <td>{{d.attributes}}</td>
      </tr>
    </tdata>
</table>

Plunker Demo

Upvotes: 1

Related Questions