AngularJS自定义过滤器重复项

时间:2018-12-11 13:39:24

标签: angularjs

我目前遇到一个有关自定义过滤器的问题。我有一个名为'cves'的CVE对象数组(在我的范围内),对于每一项,我都使用ng-repeat在表中生成tr行。

这是CVE的全局结构:

cve: {
  id: integer,
  cve: string,
  summary: text,
  description: text,
  cvss:{
    score: float,
    vector: string
  }
}

这是我的HTML代码

<input type='text' ng-model='searchField'/>
       ....
       <tr ng-repeat="cve in cves | cveFilter:[ad_filters, searchField] as filtered_cves"
            ng-if="cves.length > 0">
            <td colspan="7" class="no-padding">
               //printing infos in a custom directive
            </td>
        </tr>
        ....

这是我的过滤器:

.filter('cveFilter', function () {
    return function (cves, params) {
        console.log(cves);
        let items = {
            ids: params[0],//the ids (array of ids)
            text: params[1],//the text
            filtered_cves: []//the output
        };
         // for each cve, if its ID is in items.ids
         // AND if one of the property of the CVE match with items.text
         // push it to items.filtered_cves


        cves.forEach(function (cve) {
            if (
                items.ids.includes(cve.id) &&
                (
                    cve.cve.match(items.text) ||
                    cve.summary.match(items.text) ||
                    cve.description.match(items.text) ||
                    cve.cvss.score.match(items.text) ||
                    cve.cvss.vector.match(items.text)
                )
            ) {
                items.filtered_cves.push(cve)
            }
        });

        return items.filtered_cves;
    };
});

我的问题如下:我的过滤器似乎可以正常工作,它只保留匹配的CVE,但是将每个CVE重复显示。这意味着,如果我在$ scopes.cves数组中有6个cves,则在html表中将有12行。

这是我的第一个自定义过滤器,但我认为这是一个愚蠢的错误。

你知道我失败了吗?

先谢谢您

1 个答案:

答案 0 :(得分:0)

它正在复制数据,我没有空行。

如果我打印$ scope.filtered_cves的内容,我将得到16个元素(假设我应该得到8个元素)。

我之前没有提到,但是$ scope.ad_filters是我要显示的CVE ID数组。仅当CVE的ID在$ scope.ad_filters中并且其属性之一与输入表单文本的内容匹配时,才会显示CVE。

我目前无法截图,我需要放置虚假数据。

这是我的过滤器的更新代码(什么都没有改变,只是添加了一些功能):

.filter('cveFilter', function () {
    return function (cves, params) {
        let items = {
            ids: params[0],
            text: params[1],
            filtered_cves: []
        };

        cves.forEach(function (cve) {
            console.log(cve);
            if (items.ids.includes(cve.id)) {
                if (items.text === '' || items.text === null || items.text === undefined ||
                    (
                        cve.cve.toString().includes(items.text) ||
                        cve.summary.toString().includes(items.text) ||
                        cve.description.toString().includes(items.text) ||
                        cve.cvss.score.toString().includes(items.text) ||
                        cve.cvss.vector.toString().includes(items.text)
                    )
                ) {
                    items.filtered_cves.push(cve)
                }
            }
        });
        return items.filtered_cves;
    };
});

我运行了它,发现它执行了几次,而最后一次打印了太多行。