使用标签应用动态过滤器 [英] Apply dynamic filters using Tags
问题描述
我有一个使用 ng-repeat 显示在表格中的元素列表.我想应用使用标签添加的动态过滤器(ng-tags-input).此标签输入生成我想用作过滤器的动态标签.
I have a list of elements which is displayed in a table using ng-repeat. I want to apply dynamic filters which are added using Tags(ng-tags-input). This tag input generates dynamic tags which I want to use as filters.
这是我创建的 plunk.我如何使用这些标签中的条目来创建过滤器.
Here is the plunk I have created. How can I use entries from these tags to create filters.
对于我尝试过的单个元素
For a single element i tried
<body ng-controller="MainCtrl">
<tags-input ng-model="tags"></tags-input>
<p>Model: {{tags}}</p>
<table border=1 cellpadding=10px>
<tr ng-repeat = "t in tableData | filter:tags[0].text">
<td>{{t.data1}}</td>
<td>{{t.data2}}</td>
</tr>
</table>
</body>
但这将只需要一个元素.我想应用 tags
的整个条目作为过滤器.
but this will take only a single element. I want to apply entire entries of tags
to be a filter.
我在 SO 上看到了其他问题,但他们已将过滤器应用为
I have seen other questions on SO, but they have filters applied as
这是小提琴之一.我无法从 JSON 数组应用过滤器.我该怎么做? Here is one of the fiddle. I am not able to apply filter from JSON Array.
How can I do this? 如果您想包含属性值至少与其中一个标签匹配的项目,您可以像这样定义自定义过滤器: If you want to include items that have a property-value that matches at least one of the tags, you can define your custom filter like this: 然后像这样使用它: 另请参阅此简短演示. See, also, this short demo. 这篇关于使用标签应用动态过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
推荐答案
app.filter('filterByTags', function () {
return function (items, tags) {
var filtered = []; // Put here only items that match
(items || []).forEach(function (item) { // Check each item
var matches = tags.some(function (tag) { // If there is some tag
return (item.data1.indexOf(tag.text) > -1) || // that is a substring
(item.data2.indexOf(tag.text) > -1); // of any property's value
}); // we have a match
if (matches) { // If it matches
filtered.push(item); // put it into the `filtered` array
}
});
return filtered; // Return the array with items that match any tag
};
});
<tr ng-repeat="t in tableData | filterByTags:tags">
登录
关闭