首页 > 解决方案 > 如何根据我的 ng-model 过滤 ng-reapet 值?

问题描述

Angular 初学者,所以这听起来可能有点愚蠢,但还没有找到答案。

我有两个选择框 - 一个描述了我用作ng-model=module( [x,y,z]) 的模块。
第二个是一个数组,在每个索引中我都有一个具有 3 个属性的数组 - id、name 和 module( [1, "first", x])

我正在使用ng-repeat我的第二个选择框,我想根据模块和第三个索引进行过滤。
基本上,它是这样的:"option in options | filter: module === secondbox[2]",但显然我做错了什么,也许是语法。

请协助我正确执行。谢谢!

标签: javascriptangularjs

解决方案


我认为最好为此编写一个自定义过滤器:

.filter('moduleMatch', function() {
  return function(items, module, itemIndex, moduleIndex) {
    let out = [];

    // make sure a filter value was supplied
    if (module) {
      items.forEach(i => {
        if (i[itemIndex] === module[moduleIndex]) {
          out.push(i);
        }
      });

      // return the items that matched the filter value
      return out;
    }

    // no filter value was supplied - return the unfiltered collection
    return items;
  }
})

然后在第二个选择中使用它:

"option in options | moduleMatch: module:2:2"

推荐阅读