在我的Angular模板上,有一组级联下拉列表(Country,State,City),一个Add按钮,以及每行上有Delete按钮的表。下拉列表中的所有数据都是从加载时未经过滤的asp.net webapi中检索的。我正在尝试使用过滤器进行流动:
表数据是具有7个字段(id,countryId,country,stateId,state,cityId,city)的对象数组,如下所示。
[{
id: 1,
level1id: 101,
level1: 'USA',
level2id: 39,
level2: 'California',
level3id: 4210,
level3: 'San Diego'
}, {
id: 19,
level1id: 101,
level1: 'USA',
level2id: 33,
level2: 'Oregon',
level3id: 5905,
level3: 'Portland'
}, {
id: 1,
level1id: 101,
level1: 'USA',
level2id: 690,
level2: 'Washington',
level3id: 1223,
level3: 'Seattle'
}]
应用过滤器后,西雅图,波特兰和圣地亚哥将从下拉列表中删除。
[{
id: 3521,
city: 'San Francisco'
}, {
id: 5234,
city: 'Los Angeles'
}, {
id: 9792,
city: 'New York'
}, {
id: 8899,
city: 'Chicago'
}]
答案 0 :(得分:0)
您可以创建一个自定义过滤器,它将接收原始城市数组(进入下拉列表的数组)和所选城市列表(进入表格的城市)并过滤选定的城市所有城市的清单。
根据您的对象,假设level3id
是您要过滤的对象,您可以使用此对象:
// This is the custom filter - add it to your model
app.filter('selectedCities', function() {
/**
* This will be the returned filter function
* input is the list of cities that needs to be filtered
* selected is the list of items in the table
*/
return function(input, selected) {
var selected_cities = {}
var output = [];
//first we create hash map with all the selected cities
//This will enable us to locate a selected city in ~O(1)
angular.forEach(selected, function(selected_city) {
selected_cities[selected_city.level3id] = true;
})
/**
* now we go through the cities.
* we check if the city is in the hash of selected cities
* if its not there - we add it to the output
*/
angular.forEach(input, function(city) {
if (!(city.id in selected_cities)) {
output.push(city)
}
})
return output;
}
});
在下拉列表中,您可能有一些像ng-repeat = "city in cities"
这样的循环,并且假设表数据对象名称为table_selected_data
,因此您可以像这样使用过滤器:
ng-repeat = "city in cities | selectedCities:table_selected_data"