Javascript 使用自定义筛选器筛选嵌套的ng重复
看来我要找的是定制过滤器。在过滤元素时,我会寻找一种特定的行为。我正在寻找一个统一的搜索栏,返回所有组名匹配失败的学生的整个匹配组名,只返回匹配学生的组名 例如,通过搜索“呃”,结果应该是“招潮蟹”和“火爆船长”的完整列表,但“金熊”应该只显示德鲁·帕克和埃里克 plunkr当前演示了默认的过滤器行为。如果将HTML中的过滤器更改为my custom filter,Javascript 使用自定义筛选器筛选嵌套的ng重复,javascript,angularjs,filtering,angularjs-ng-repeat,Javascript,Angularjs,Filtering,Angularjs Ng Repeat,看来我要找的是定制过滤器。在过滤元素时,我会寻找一种特定的行为。我正在寻找一个统一的搜索栏,返回所有组名匹配失败的学生的整个匹配组名,只返回匹配学生的组名 例如,通过搜索“呃”,结果应该是“招潮蟹”和“火爆船长”的完整列表,但“金熊”应该只显示德鲁·帕克和埃里克 plunkr当前演示了默认的过滤器行为。如果将HTML中的过滤器更改为my custom filter,nestFilter(第27行),并遵循控制台日志,则可以看到返回的数组正在更新,同时添加和删除搜索词,但没有重新绘制元素。这是我
nestFilter
(第27行),并遵循控制台日志,则可以看到返回的数组正在更新,同时添加和删除搜索词,但没有重新绘制元素。这是我的过滤器
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
存在两个问题,其中一个问题是您正在修改原始数组(设置coquent.students=matchedStudents
)
下面是nestFilter
()
顺便说一句,因为您的RegExp是循环不变的,所以您应该在循环之外构造一个实例,然后重用。此外,由于您的用户提供的输入可能包含您希望逐字匹配的正则表达式字符(例如“*”),因此您需要转义输入()。
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;
};
});