1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That just won't work, the filter filter does bind to a function that "Selects a subset of items from array and returns it as a new array.". It takes an array as parameter, and converts the entire one to a new one. It doesn't get called on each element.
@CyrilCHAPON It works... I added a plunker to show you.
hum ok sorry. I misread an didn't realize he's using ui-select. Be careful though, your code only works with ui-select and not native angular's select. I'd add that your code inly works in this situation so that's a one-shot filter.
@CyrilCHAPON That's what seems to be his scenario :)
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.