AngularJS: 使用 ng-options 过滤

AngularJS: Filter with ng-options

我可以在筛选整个对象时对我的选项使用筛选器,但我只想将筛选器应用于名称 属性,但我无法正常工作。无论在输入中键入什么,下面的结果都不会改变 select 中显示的内容。我根据此处找到的答案 - 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" >

但是,如果我有这个,过滤器就可以工作 -

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

问题是我不想按整个对象进行过滤,否则您可能会得到看似随机且不需要的结果。

您可以将过滤器指定为参数名称等于搜索字段的对象。 为了您的目的,请尝试将 searchText.Name 作为搜索文本的模型。它应该只按 "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">

您可以通过这种方式创建自己的过滤器:

AvailableUserGroups|byNameInSearchText:searchText

使用此声明:

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