【发布时间】:2015-08-17 14:35:40
【问题描述】:
我想插入内容,以便在复选框旁边打印每个学生的位置,而不会出现任何重复的位置。我的 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 在进入另一个组时会重置。我不确定如何使用嵌套对象来解决这个问题。有人可以向我解释我做错了什么吗?
【问题讨论】:
-
是的..确实是因为你进入了另一个组。
-
在提问时注意您使用的是哪个版本的 Angular 也很有帮助,有时在特定版本中事情会更容易。
标签: javascript json angularjs filter unique