我有一个使用 ng-repeat 显示在表格中的元素列表。我想应用使用标签(ng-tags-input)添加的动态过滤器。此标签输入生成我想用作过滤器的动态标签。
这是 plunk我创造了。我如何使用这些标签中的条目来创建过滤器。
对于单个元素我试过了
<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
的整个条目成为一个过滤器。
我在 SO 上看到了其他问题,但它们应用了过滤器
<tr ng-repeat = "t in tableData | filter:{data1:someFilteData}">
这是 fiddle 之一.我无法从 JSON 数组应用过滤器。 我该怎么做?
最佳答案
如果您想要包含属性值与至少一个标签相匹配的项目,您可以像这样定义您的自定义过滤器:
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">
另请参阅此 short demo .
关于javascript - 使用标签应用动态过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785592/