使用过滤器来创建数组,然后使用该数组来过滤NG选项 [英] Using filter to create array, then using that array to filter ng-options

查看:190
本文介绍了使用过滤器来创建数组,然后使用该数组来过滤NG选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我使用 isteven的多选择输出一个从选择元素的多重选择对象的数组。

  1. I am using isteven-multi-select to output an array of objects from a select element's multiple selections.

[
  { category: "Adventure", ticked: true },
  { category: "Strategy", ticked: true }
]


结果
2.然后用angular.forEach物体的阵列换入类别值的阵列


2. Then using angular.forEach to change the array of objects into an array of the category values.

$scope.testOutput = function () {
    angular.forEach($scope.output, function(value, prop, obj) {
        var categoryFiltered = [];

        categoryFiltered.push(value.category);
        console.log(categoryFiltered);
    });
};

categoryFiltered = ["Adventure", "Strategy"];

结果
3.现在我需要使用categoryFiltered阵列中的一个NG重复过滤掉其他类别。


3. Now I need to use the categoryFiltered array to filter out the other categories in an ng-repeat.

HTML

ul
  li(ng-repeat='item in items | filter: {categories: categoryFiltered')

结果
    MongoDB的填充项


MongoDB populating items

        {
          year: 1962,
          categories: ["Adventure"]
        }, {
          year: 1972,
          categories: ["Fishing"]
        }, {
          year: 1982,
          categories: ["Strategy"]
        }

什么是实现这一目标的最佳途径?

What is the best way to achieve this?

推荐答案

编写自定义过滤器,那么你可以过滤但是你喜欢的类别(例如,你想过滤匹配指定的所有类别?还是只有部分项目?)。

Write a custom filter, then you can filter the categories however you like (eg. do you want to filter items that match ALL the categories specified? Or only some?).

下面是一个plunkr例如: http://plnkr.co/edit/Lv11QWumN7ktjfS15RpY? p = preVIEW

Here's a plunkr example: http://plnkr.co/edit/Lv11QWumN7ktjfS15RpY?p=preview

它的主要组成部分,以定义过滤器:

Main part of it, to define your filter:

app.filter('filterByCategories', function() {
    return function(input, categories) {
      // Input is the array to be filtered, categories is the list of
      // categories to filter by
      input = input || [];
      categories = categories || [];

      var output = [];
      for (var i = 0; i < input.length; i++) {
        for (var j = 0; j < categories.length; j++) {
          // If input matches any of the categories, then add it to the list
          if (input[i].categories.indexOf(categories[j].trim()) >= 0) {
            output.push(input[i]);
            break;
          }
        }
      }

      return output;
    };
  })

然后就可以使用自定义过滤器,像这样:

Then you can use the custom filter like so:

&LT;李NG重复=数据项| filterByCategories:filterStr.split('')&GT;

或者

&LT;李NG重复=数据项| filterByCategories:['冒险','策略']&GT;

这篇关于使用过滤器来创建数组,然后使用该数组来过滤NG选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆