在一个表中重复ng-repeat

时间:2015-01-27 13:33:59

标签: json angularjs

{
  "title": "hello"
  "fights": [{
    "round": "fights round 2",
    "teams" : [
    {
      "name": "teamA",
      "members": [
        {"name": "alex", "age": 31},
        {"name": "alex2", "age": 32}
      ]
    },{
      "name": "teamB",
      "members": [
        {"name":"niko", "age": 31}
        {"name":"niko2", "age": 32}
      ]
    }
    ]
  }, {
    "round": "fights round 2",
    "teams" : [
    {
      "name": "teamA2",
      "members": [
        {"name": "alex2", "age": 31},
        {"name": "alex22", "age": 32}
      ]
    },{
      "name": "teamB2",
      "members": [
        {"name":"niko2", "age": 31}
        {"name":"niko22", "age": 32}
      ]
    }
    ]
  }]
}

或查看pastebin,http://pastebin.com/gfjU8ZiJ

现在我正在努力将titleround以及每场战斗中的所有团队成员提取到一张桌子中,这样就像这样......

<table>
    <tr ng-repeat="items in $root.fights">
        <td>{{item.title}}</td>
        <td>fightround2</td>
        <!-- and here to fetch all the members from each team -->
        <td>alex</td>
        <td>alex2</td>
        <td>niko</td>
        <td>niko2</td>
        <!-- here to fetch team from fights[1] -->
    </tr>
</table>

如何使用ng-repeat完成此操作?不幸的是,JSON如何来,我无法改变它,只是从它读取。谢谢!

1 个答案:

答案 0 :(得分:1)

将HTML更改为以下

<table>
    <tr ng-repeat="items in $root.fights track by $index">
        <td>{{item.title}}</td>
        <td>fightround2</td>
        <td ng-repeat="member in getTeamMembers(item)">{{member.name}}</td>
        <!-- and here to fetch all the members from each team -->
        <td>alex</td>
        <td>alex2</td>
        <td>niko</td>
        <td>niko2</td>
    </tr>
</table>

将此添加到您的控制器

$scope.getTeamMembers = function (item) {
    var members = [];

    for (var i=0; i < item.fights.length; i++) {
        var fight = item.fights[i];
        for (var j = 0; j < fight.teams.length; j++){
            var team = fight.teams[j];
            for(var k=0; k < team.members.length; k++) {
                Array.prototype.push.apply(members, team.members[k]);
            }
        }
    }

    return members;
};