简体   繁体   English

按数组中的类别进行角度过滤

[英]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!). 我有一个产品JSON文件,并且JSON文件中的每个产品都有它自己的标签集(其中一些标签在其他产品之间共享!)。 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? 我可以使用ng-repeat创建在数组中找到的标签列表,然后可以单击这些生成的标签,然后通过单击的标签过滤页面上的项目吗? 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. 我对Angular还是很陌生,所以不确定它的局限性。

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: 现在,您可以为这些属性创建HTML标记列表:

<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: 单击一个属性将设置一个selectedAttribute变量,该变量用于过滤产品列表:

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

Plunker Demo 柱塞演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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