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

AngularJS中如何基于ng-model值仅过滤ng-repeat的category字段?

解决AngularJS ng-repeat仅针对指定字段过滤的问题

嘿,我完全懂你遇到的问题——AngularJS默认的filter过滤器会遍历对象的所有属性去匹配关键词,所以才会出现全局匹配的情况。要实现只针对category字段过滤,其实只要调整一下过滤器的写法就搞定了!

具体解决方案

把原来的全局过滤写法:

ng-repeat="question in questions | filter:kpcategory"

改成指定字段的过滤写法,用对象字面量明确告诉过滤器只在category字段中匹配:

ng-repeat="question in questions | filter:{category: kpcategory}"

完整代码示例

<!-- 你的输入框 -->
<input type="text" ng-model="kpcategory" value="Social Psychology" placeholder="搜索分类">

<!-- 仅针对category字段过滤的列表 -->
<div ng-repeat="question in questions | filter:{category: kpcategory}">
  <h4>{{question.name}}</h4>
  <p>分类:{{question.category}}</p>
</div>

补充说明

  • 这个写法会严格只匹配question对象里的category属性和kpcategory的值,完全不会涉及其他字段(比如name),刚好符合你的需求。
  • 默认情况下过滤器是大小写不敏感的,如果需要精确匹配(区分大小写),可以加上第三个参数:true:
    ng-repeat="question in questions | filter:{category: kpcategory}:true"
    

内容的提问来源于stack exchange,提问作者R. Mani Selvam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:18:28