应用动态过滤器使用标签 [英] Apply dynamic filters using Tags
问题描述
我有一个使用ng-repeat在表格中显示的元素列表。我想应用使用标签添加的动态过滤器()。这个标签输入生成我想用作过滤器的动态标签。
以下是我创造了。
对于我试过的单个元素
< body ng-controller =MainCtrl>
< tags-input ng-model =tags>< / tags-input>
< p>模型:{{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>
但这只会占用一个元素。我想应用标记
的整个条目作为过滤器。
我已经看到了关于SO的其他问题,但他们在tableData | filter:{data1:someFilteData}>中应用了如下过滤器:
< tr ng-repeat = code>
这是小提琴。我无法从JSON数组应用过滤器。
如何做到这一点?
如果您想包含具有匹配的属性值的项目至少有一个标签,你可以像这样定义你的自定义过滤器:
$ $ $ $ $ c $ app.filter('filterByTags',function() {
return function(items,tags){
var filtered = []; //只在这里放入符合
(items || [])。forEach(function(item){ //检查每个项目
var matches = tags.some(function(tag){//如果有一些标签
return(item.data1.indexOf(tag.text)> -1) | //这是一个子字符串
(item.data2.indexOf(tag.text)> -1); //任何属性的值
}); //我们有一个匹配
if(matches){//如果匹配
filtered.push(item); //将其放入`filtered`数组
}
});
return filtered; //返回与任何标签
}匹配的项目的数组;
});
然后像这样使用它:
<$ < code>< tr ng-repeat =t in tableData | filterByTags:tags>
另请参阅 短小演示 。
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.
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>
but this will take only a single element. I want to apply entire entries of tags
to be a filter.
I have seen other questions on SO, but they have filters applied as
<tr ng-repeat = "t in tableData | filter:{data1:someFilteData}">
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:
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
};
});
And the use it like this:
<tr ng-repeat="t in tableData | filterByTags:tags">
See, also, this short demo.
这篇关于应用动态过滤器使用标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!