AngularJS:按 ID 数组过滤

AngularJS: Filter by Array of Ids

我正在使用 ui-select 来显示一个下拉列表,其中包含我以 json 响应形式从 Web 服务获取的值。我有另一个数组,其中 "id"s 只是整数值。我想通过数组的值过滤 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, and not angular-UI's select。因此,这个答案并不真正适合这个问题,但我会把它留在这里供社区搜索本机解决方案,以及 lodash 可读性的东西。

为了便于阅读,我会使用简单的 filter, maybe with 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>