gpt4 book ai didi

javascript - 使用自定义过滤器通过嵌套 ng-repeats 进行过滤

转载 作者:行者123 更新时间:2023-11-28 08:18:20 25 4
gpt4 key购买 nike

看来自定义过滤器就是我在这里所追求的。在过滤元素时,我正在寻找一种特定的行为。我希望创建一个统一的搜索栏,以返回整个匹配的小组名称,其中包含所有未通过小组名称匹配的学生,以及仅包含匹配的学生的小组名称。

Here's my plunker with all the code

例如,通过搜索“er”,结果应该是“FiddleER Crabs”和“FiERy Skippers”的完整列表,但“Golden Bears”应该只显示 Drew ParkER 和 ERic。

plunkr 当前演示了默认过滤器行为。如果将 HTML 中的过滤器更改为我的自定义过滤器,即第 27 行的 nestFilter,并跟踪控制台日志,您可以看到返回的数组正在随着搜索词的添加和删除而更新,但元素没有被重绘。这是我的过滤器

bootTracker.filter('nestFilter', function() {

return function(elements, input) {

var filteredCohorts, filteredCohortsStudents;
filteredCohorts = [];
filteredCohortsStudents = [];

console.log(elements);

angular.forEach(elements, function(cohort) {

var matchedStudents;
matchedStudents = [];

if (cohort.name.match(new RegExp(input, 'ig'))) {
filteredCohorts.push(cohort);
}

angular.forEach(cohort.students, function(student) {
if (student.name.match(new RegExp(input, 'ig'))) {
return matchedStudents.push(student);
}
});

cohort.students = matchedStudents;
if (cohort.students.length > 0) {
return filteredCohortsStudents.push(cohort);
}
});

console.log(filteredCohorts);
return filteredCohorts;
};
});

最佳答案

您的 nestFilter 存在几个问题,其中之一是您正在修改原始数组(设置 cohort.students =matchedStudents)。

这是 nestFilter 的工作版本 ( see this Plunker for a demo )

bootTracker.filter('nestFilter', function() {
return function(elements, input) {
var filteredCohorts = [];
console.log(elements);
angular.forEach(elements, function(element) {
if (element.name.match(new RegExp(input, 'ig'))) {
filteredCohorts.push(element);
} else {
var matchedStudents = [];
angular.forEach(element.students, function(student) {
if (student.name.match(new RegExp(input, 'ig'))) {
matchedStudents.push(student);
}
});
if (matchedStudents.length > 0) {
var cohort = angular.extend({}, element);
cohort.students = matchedStudents;
filteredCohorts.push(cohort);
}
}
});
console.log(filteredCohorts);
return filteredCohorts;
};
});

关于javascript - 使用自定义过滤器通过嵌套 ng-repeats 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com