AngularJS: Filter with ng-options

3.3k Views Asked by At

I am able to use filters on my options when filtering the entire object, but I only want the filter apply to the name property, which I can't get working. The below results in no changes to what is displayed in the select regardless of anything being typed in the input. I have based this on the answer found here - Use filter on ng-options to change the value displayed

<input type="search" class="form-control" placeholder="Filter user groups" results="0" ng-model="searchText" />

<select class="form-control"
        size="8"
        multiple
        ng-model="UserGroupsSelected"
        ng-options="userGroup.Id as (userGroup.Name | filter:searchText) for userGroup in AvailableUserGroups" >

However, the filter does work if I have this -

ng-options="userGroup.Id as userGroup.Name for userGroup in AvailableUserGroups | filter:searchText"

The issue being that I don't want to filter by the entire object or else you can get seemingly random and unwanted results coming up.

2

There are 2 best solutions below

1
On BEST ANSWER

You can specify filter as a object which parameter name equals search field. For your purpose try to put searchText.Name as a model for search text. It should filter object just by "Name".

<input type="search" class="form-control" placeholder="Filter user groups" results="0" ng-model="searchText.Name" />

<select class="form-control"
        size="8"
        multiple
        ng-model="UserGroupsSelected"
        ng-options="userGroup.Id as userGroup.Name for userGroup in AvailableUserGroups | filter:searchText">
0
On

You can create your own filter this way :

AvailableUserGroups|byNameInSearchText:searchText

with this declaration :

myapp.filter('byNameInSearchText', function() {
    return function(availableUserGroups,textName) {
        if (typeof textName !== "undefined" && textName !== null) {
           return availableUserGroups.filter(function(u) {
                return (u.Name != null) && u.Name.indexOf(textName) !== -1;
            });
        }
        else return availableUserGroups;
    };
});