[英]Apply dynamic filters using Tags
我有一个元素列表,使用ng-repeat在表格中显示。 我想应用使用标签( ng-tags-input )添加的动态过滤器。 此标记输入生成我想用作过滤器的动态标记。
这是我创造的插件 。 如何使用这些标记中的条目创建过滤器。
对于我试过的单个元素
<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}">
这是小提琴之一 。 我无法从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">
另见这个简短的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.