Angular 嵌套 ng-repeat 的唯一过滤器
Angular unique filter for nested ng-repeat
我想插入内容,以便它在复选框旁边打印每个学生的位置,而不会出现任何重复的位置。我的 HTML 看起来像这样:
<ul ng-repeat="group in groups">
<li ng-repeat="student in group.students | unique : 'location'">
<input type="checkbox" id="location">
<label for="location" ng-repeat="loc in student.location | unique : 'loc'">{{loc}}</label>
</li>
</ul>
我正在使用此过滤器代码过滤掉我的 JSON 文件中重复的项目。
App.js
app.filter('unique', function() {
return function(input, key) {
var uniqueList = [];
var unique = {};
for(var i = 0; i < input.length; i++) {
if(typeof unique[input[i][key]] == "undefined") {
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
我的 JSON 文件格式如下:
"groups" : [
{
"name": "a",
"students" : [
{
"student_name" : "Nate",
"location" : "California"
},
{
"student_name" : "Natalie",
"location": "Michigan"
},
{
"student_name" : "Tim",
"location" : "California"
}
]
},
{
"name" : "b",
"students" : [
{
"student_name" : "Brian",
"location" : "California"
}
]
}
]
它打印加利福尼亚密歇根加利福尼亚。我认为这是因为 uniqueList 在进入另一个组时会重置。我不确定如何处理嵌套对象。有人可以向我解释我做错了什么吗?
您将无法在过滤器中执行此操作,因为您是正确的,每个组都会重置它。您需要事先将这些组组合起来,然后循环遍历组合组。
我想插入内容,以便它在复选框旁边打印每个学生的位置,而不会出现任何重复的位置。我的 HTML 看起来像这样:
<ul ng-repeat="group in groups">
<li ng-repeat="student in group.students | unique : 'location'">
<input type="checkbox" id="location">
<label for="location" ng-repeat="loc in student.location | unique : 'loc'">{{loc}}</label>
</li>
</ul>
我正在使用此过滤器代码过滤掉我的 JSON 文件中重复的项目。
App.js
app.filter('unique', function() {
return function(input, key) {
var uniqueList = [];
var unique = {};
for(var i = 0; i < input.length; i++) {
if(typeof unique[input[i][key]] == "undefined") {
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
我的 JSON 文件格式如下:
"groups" : [
{
"name": "a",
"students" : [
{
"student_name" : "Nate",
"location" : "California"
},
{
"student_name" : "Natalie",
"location": "Michigan"
},
{
"student_name" : "Tim",
"location" : "California"
}
]
},
{
"name" : "b",
"students" : [
{
"student_name" : "Brian",
"location" : "California"
}
]
}
]
它打印加利福尼亚密歇根加利福尼亚。我认为这是因为 uniqueList 在进入另一个组时会重置。我不确定如何处理嵌套对象。有人可以向我解释我做错了什么吗?
您将无法在过滤器中执行此操作,因为您是正确的,每个组都会重置它。您需要事先将这些组组合起来,然后循环遍历组合组。