Splitting ng-repeat every 3 items

前端 未结 1 1539
庸人自扰
庸人自扰 2021-02-06 06:19

Using AngularJS, I\'m iterating over a JSON object containing an array of event objects, containing an array of competition objects.

I wish to show each event

相关标签:
1条回答
  • 2021-02-06 07:05

    You are using a table but the semantics of your data indicate you have a list of lists. You should consider outputting this with <ul><li> instead of a grid.

    <ul ng-repeat="listing in listings">
        <li>
            <h2>{{listing.name}}</h2>
            <ul ng-repeat="competition in listing.competitions">
                <li>
                  {{competition.id}} - {{competition.name}}
                </li>
            </ul>
        </li>
    </ul>
    

    You can achieve your desired layout with CSS quite easily using the above HTML. Checkout the "block grids" in Twitter Bootstrap or Foundation for examples. Tables should generally be used only for data that is actually tabular.

    However...

    You're question does still bear answering since there may be other reasons to alternate templates in the way you suggest. You could use a function for this to get things three at a time:

    <table ng-repeat="listing in listings">
        <tr>
            <th colspan="3">{{listing.name}}</th>
        </tr>
        <tr ng-repeat="group in competitions">
            <td ng-repeat="competition in group">
                {{competition.id}} - {{competition.name}}
            </td>
        </tr>
    </table>
    

    In your controller you can create a "list of lists" to bind to the nested repeaters

    // Adapted from Fresheyeball's solution
    
    $scope.competitions = []
    compSet = []
    for(var i; i < $scope.listings.competitions; i++){
       var competition = $scope.listings.competitions[i];
       if( i % 3 ){
          $scope.competitions.push(compSet);
          compSet = [];
       }
       compSet.push(competition);
    }
    
    0 讨论(0)
提交回复
热议问题