[英]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.