You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AngularJS中按属性名筛选多选下拉框选项?

AngularJS多选下拉框筛选失效的解决方法

问题原因

你代码的核心问题是ng-options中track by的位置错误——过滤器必须放在track by之前,原写法把过滤器放在track by之后,导致过滤逻辑根本没作用到数据源上,自然无法实现筛选。

修正后的代码

调整ng-options的结构,用括号包裹过滤后的数据源,确保先执行过滤再应用track by:

<label for="countryFilter">Filter</label><br>
<input id="countryFilter" ng-model="countryFilter" type="text">
<label for="countries">Countries</label><br>
<select
  id="countries"
  ng-model="countries"
  ng-options="option.name for option in (countryOptions | filter:{name: countryFilter}) track by option.id"
  multiple>
</select>

额外验证事项

  • 确认控制器中countryOptions是包含id和name字段的有效数组,比如:
    $scope.countryOptions = [
      {id: 1, name: 'China'},
      {id: 2, name: 'United States'},
      {id: 3, name: 'Germany'}
    ];
    
  • 确保输入框的ng-model="countryFilter"和ng-options中使用的过滤变量名完全一致(你原代码里这点是对的)。

可选简化写法(按需使用)

如果不需要精准匹配name字段,而是允许模糊匹配对象的所有属性,可以简化过滤器写法:

ng-options="option.name for option in (countryOptions | filter:countryFilter) track by option.id"

但这种写法会匹配对象的所有字段,比如如果某条数据的id包含输入文本,也会被筛选出来,所以精准匹配场景还是推荐用filter:{name: countryFilter}。

内容的提问来源于stack exchange,提问作者user3174311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:22:23