用于嵌套ng-repeat的Angular独特过滤器

时间:2015-08-17 14:35:41

标签: javascript json angularjs filter unique

我想插入内容,以便打印复选框旁边的每个学生位置,而不会有任何重复的位置。我的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在进入另一个组时会重置。我不确定如何使用嵌套对象来解决这个问题。有人可以向我解释我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您将无法在过滤器中执行此操作,因为您是正确的,每个组都会重置它。您需要预先组合这些组,然后循环组合组。

相关问题