STORM
STORM

Reputation: 4331

AngularJS: Filter by Array of Ids

i am using ui-select to show a dropdown list with values which i get from a webservice in form of a json response. I have another array where i have "id"s which are simply integer values. I want to filter the ui-select by the values of the array.

How could i achieve this?

Upvotes: 1

Views: 1894

Answers (2)

Cyril CHAPON
Cyril CHAPON

Reputation: 3747

Edit: Following solution only works with angular native select, and not angular-UI's select. As a consequence, this answer doesn't realy fit the question, but I'll leave it here for community searching for native solutions, and for lodash readability stuff.

I'd use a simple filter, maybe with lodash for readability

Controller

$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);
    });
}

Template

<select ng-model="selectedBean" ng-options="bean.name for bean in beans | filter:idInArray:idsFilter">
</select>

Upvotes: 0

Omri Aharon
Omri Aharon

Reputation: 17064

You can create your own custom filter, which is simply a function that's defined in your controller, and it will look like this:

$scope.customFilter = function(item) {
    var arr = [1,25,8]; //Your integer array here
    return arr.indexOf(item) > -1; //returns true if exists
}

And your HTML will be:

<ui-select-choices repeat="x in myArray | filter: customFilter">
    {{x}}
</ui-select-choices>

Updated a Plunker I found to demonstrate. Look how the color list is filtered according to the ['Green', 'Red'] array in the filter function.

Upvotes: 2

Related Questions