如何在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
相关产品推荐
相关产品推荐

