Reputation: 479
I need some help figuring out how I can use the AngularJS filter to only show the options that match my condition.
I have the below array.
var users = [
{'id':0, 'name':'John', 'roles':['Admin']},
{'id':1, 'name':'Alice', 'roles':['Admin', 'Tech']},
{'id':2, 'name':'Sam': 'roles':['Tech']}
]
I render all the users on a <select>
list with the below code. But I only want to show the users who's role is "Tech". I went through a few other answers on here but they all use the filter with an object, I'm trying this with an array.
<select data-ng-options="item.id as item.name for item in users"></select>
I've tried to only show the options with data-ng-if="item.roles.indexOf('Tech') > -1"
on the <select>
tag but that condition is never met so the dropdown is not shown at all (which makes sense).
I also tried to use data-ng-options="item.id as item.name for item in users | filter:{item.roles:'Tech'}"
with the filter, but that fails with an AngularJS parse error.
Not sure how I can filter by array values.
Upvotes: 1
Views: 1547
Reputation: 4448
Your logic in your last attempt is correct but you have a small syntax error. Try the following
<select ng-model="selectedValue" data-ng-options="item.id as item.name for item in users | filter: { roles: ('Tech') }"></select>
You can also create your own custom filter function for this
html
<select ng-model="selectedValue" data-ng-options="item.id as item.name for item in users | filter:customFilter"></select>
js
$scope.customFilter = function(row){
if(row.roles.includes("Tech")){
return true;
}
else{
return false;
}
}
Upvotes: 2