[英]AngularJS Custom Filter in ng-repeat Table
I can filter values in table (especific column) with this custom filter.我可以使用此自定义过滤器过滤表(特定列)中的值。 Data come from an array of a multiple select input数据来自多选输入的数组
Complete Example: http://jsfiddle.net/d1sLj05t/1/完整示例: http : //jsfiddle.net/d1sLj05t/1/
myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
var filterObj = {
data:items,
filteredData:[],
applyFilter : function(obj,key){
var fData = [];
if(this.filteredData.length == 0)
this.filteredData = this.data;
if(obj){
var fObj = {};
if(angular.isString(obj)){
fObj[key] = obj;
fData = fData.concat($filter('filter')(this.filteredData,fObj));
}else if(angular.isArray(obj)){
if(obj.length > 0){
for(var i=0;i<obj.length;i++){
if(angular.isString(obj[i])){
fObj[key] = obj[i];
fData = fData.concat($filter('filter')(this.filteredData,fObj));
}
}
}
}
if(fData.length > 0){
this.filteredData = fData;
}
}
}
};
if(keyObj){
angular.forEach(keyObj,function(obj,key){
filterObj.applyFilter(obj,key);
});
}
return filterObj.filteredData;
}
}]);
<tr ng-repeat="emp in empList | filterMultiple:{dept:selected}">
Perfect when values exists like "sales" or "account", but when the value not exist in the table, return all data (when i choose "not" or combinate "not" and "sales").当值存在如“sales”或“account”时完美,但当表中不存在该值时,返回所有数据(当我选择“not”或组合“not”和“sales”时)。 I expected an empty result o just the selected values我期望一个空结果 o 只是选定的值
I think you can accomplish what you want with a much simpler filter.我认为你可以用一个更简单的过滤器来完成你想要的。 You might want to try something like this instead:你可能想尝试这样的事情:
myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
//If the value isn't defined, don't filter at all.
if (keyObj.value == undefined) {
return items;
}
//Use javascript's native Array.filter() to get only the items that match.
return items.filter(function(item) {
//Keep any items whose specified attribute includes the selected value
return item[keyObj.column].includes(keyObj.value);
})
}
}]);
And a slight change in your HTML:你的 HTML 略有变化:
<tr ng-repeat="emp in empList | filterMultiple:{column:'dept', value:selected}">
I'm not sure what you mean by " combinate 'not' and 'sales' ", but I think this will get you moving in the right direction.我不确定你所说的“结合‘非’和‘销售’”是什么意思,但我认为这会让你朝着正确的方向前进。
Here are some related links, in case you're not familiar with some of the things I'm doing in the code:以下是一些相关链接,以防您不熟悉我在代码中所做的一些事情:
Documentation for Array.filter -- MDN Array.filter 的文档 -- MDN
Array.filter is better than $filter('filter') -- StackOverflow Array.filter 优于 $filter('filter') -- StackOverflow
Documentation for String.includes -- MDN String.includes 的文档——MDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.