angularjs - 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 个 cve,我的 html 表中将有 12 行。
这是我的第一个自定义过滤器,但我认为这是一个愚蠢的错误。
你知道我哪里失败了吗?
提前谢谢你,
解决方案
它正在复制数据,我没有得到空行。
如果我打印 $scope.filtered_cves 的内容,我会得到(假设我应该得到 8 个)16 个元素。
我之前没有提到,但 $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;
};
});
我运行它,我注意到它被执行了好几次,最后一次它打印了两次太多的行。
推荐阅读
- botframework - 如何在 Microsoft Teams 应用中代表用户发布消息?
- c++ - 使用 gcc 编译具有 inline-assembly 和 Intel 语法的 c++ 代码并实现它
- azure - azure 应用服务身份验证模块是否支持 azure aad b2c?
- elasticsearch - elasticsearch Basic 许可证中每个集群的最大节点数是多少?
- c# - 我想创建一个共享数据库 c# windows 窗体应用程序?
- bash - $RANDOM 从函数返回时保持不变
- sorting - 是否可以在threejs中手动对对象进行排序?
- c# - Linq 复杂内连接
- spring-boot - 在 RabbitMQ 中使用 @StreamListener 从两个不同的队列中消费多条消息
- excel-2010 - 如何让 Excel 根据表中的最大值返回一个值?