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

AngularJS ng-repeat中filter函数无法传参,type值始终为0

AngularJS自定义Filter无法接收第二个参数的原因及解决方案

问题原因

AngularJS内置的filter过滤器语法规则是:array | filter:expression:comparator。当你把自定义函数myFilter作为expression时,这个函数的默认参数顺序是**(item, index, array)**,而你写在filter后面的1/2/3/4会被当作comparator(比较器)参数,并不会传递给myFilter。所以你的type变量实际接收的是循环的index值(初始为0),导致无法拿到预期的参数。

解决方案

要给自定义过滤函数传递参数,需要用闭包工厂函数的方式:让myFilter先接收你要传入的type参数,再返回一个真正的过滤函数,这个过滤函数通过闭包捕获type值。

修改后的JS代码

$scope.myFilter = function(type) {
  // 返回真正的过滤函数,闭包捕获type参数
  return function(item) {
    if (item == undefined) return false;
    
    let condition1 = false;
    let condition2 = false;
    switch(type) {
      case 1:
        condition1 = item.DetailType === 'G';
        condition2 = item.IsException === false;
        break;
      case 2:
        condition1 = item.DetailType === 'E';
        condition2 = item.IsException === false;
        break;
      case 3:
        condition1 = item.DetailType === 'G';
        condition2 = item.IsException === true;
        break;
      case 4:
        condition1 = item.DetailType === 'E';
        condition2 = item.IsException === true;
        break;
    }
    return condition1 && condition2;
  };
};

修改后的HTML代码

<table>
  <tbody>
    <tr ng-repeat="emp in details | filter:myFilter(1)"></tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr ng-repeat="emp in details | filter:myFilter(2)"></tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr ng-repeat="emp in details | filter:myFilter(3)"></tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr ng-repeat="emp in details | filter:myFilter(4)"></tr>
  </tbody>
</table>

补充说明

这样修改后,myFilter(1)会立即执行并返回一个绑定了type=1的过滤函数,AngularJS在执行filter时会调用这个返回的函数,此时就能正确使用你传入的type值进行过滤逻辑判断。

内容的提问来源于stack exchange,提问作者Hiếu Lưu Trọng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:25:17