【发布时间】:2015-04-27 17:42:58
【问题描述】:
我正在使用 ui-select 显示一个下拉列表,其中包含我从 web 服务以 json 响应的形式获得的值。我有另一个数组,其中有“id”,它们只是整数值。我想通过数组的值过滤 ui-select。
我怎样才能做到这一点?
【问题讨论】:
我正在使用 ui-select 显示一个下拉列表,其中包含我从 web 服务以 json 响应的形式获得的值。我有另一个数组,其中有“id”,它们只是整数值。我想通过数组的值过滤 ui-select。
我怎样才能做到这一点?
【问题讨论】:
您可以创建自己的自定义过滤器,它只是在您的控制器中定义的一个函数,它看起来像这样:
$scope.customFilter = function(item) {
var arr = [1,25,8]; //Your integer array here
return arr.indexOf(item) > -1; //returns true if exists
}
您的 HTML 将是:
<ui-select-choices repeat="x in myArray | filter: customFilter">
{{x}}
</ui-select-choices>
更新了我发现的Plunker 来演示。看看颜色列表是如何根据过滤函数中的['Green', 'Red']数组进行过滤的。
【讨论】:
编辑:以下解决方案仅适用于angular native select,不适用于angular-UI's select。因此,这个答案并不真正适合这个问题,但我将把它留在这里,以供社区搜索本地解决方案和 lodash 可读性的东西。
为了便于阅读,我会使用简单的filter,可能会使用lodash
控制器
$scope.selectedBean = null;
$scope.beans = [{id:1},{id:2}];//database lookup or something
$scope.idsFilter = [1, 2];//ng-model or something
$scope.idInArray = function(beans, ids) {
return _.filter(beans, function(bean){
return _.contains(ids, beans.id);
});
}
模板
<select ng-model="selectedBean" ng-options="bean.name for bean in beans | filter:idInArray:idsFilter">
</select>
【讨论】: