【问题标题】:AngularJS: Filter with ng-optionsAngularJS:使用 ng-options 过滤
【发布时间】:2015-06-15 09:41:40
【问题描述】:

过滤整个对象时,我可以在我的选项上使用过滤器,但我只希望过滤器应用于 name 属性,而我无法正常工作。无论在输入中键入任何内容,以下内容都不会更改选择中显示的内容。我基于这里找到的答案 - 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"

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

【问题讨论】:

    标签: angularjs angularjs-filter


    【解决方案1】:

    您可以将过滤器指定为参数名称等于搜索字段的对象。 出于您的目的,尝试将searchText.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">
    

    【讨论】:

    • 有了这个解决方案,可以使用 ng-options orderBy, track by, ... 非常有用。谢谢!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多