简体   繁体   中英

nested arrays with ng-repeat and table html

I want to take this json place it into a HTML table.

    "columns" : [ 
    {
        "id" : 0,
        "column_name" : "Column 1",
        "cards" : [ 
            {
                "id" : 0,
                "task" : "Task 1"
            }, 
            {
                "id" : 1,
                "task" : "Task 2"
            }
        ]
    }, 
    {
        "id" : 1,
        "column_name" : "Column 2",
        "cards" : [ 
            {
                "id" : 0,
                "task" : "Task 3"
            }
        ]
    }]

I have done quite a bit of searching on SO and cannot find why it is not doing what I expect.

https://jsfiddle.net/6nh100ca/9/

This is what I am expecting.

**Column 1 | Column 2**
Task 1   | Task 3
Task 2   | 

https://stackoverflow.com/a/20063394/3279550 http://www.bennadel.com/blog/2456-grouping-nested-ngrepeat-lists-in-angularjs.htm https://stackoverflow.com/a/26607425/3279550

This is what I have

    <table >
        <thead >
            <tr>
                <th ng-repeat="column in entity.columns">{{column.column_name}}</th>
            </tr>
        </thead>
        <tbody ng-repeat="column in entity.columns" >
            <tr ng-repeat="card in column.cards">
                <td >{{card.task}}</td>
            </tr>
        </tbody>
    </table>

column.columnName should be column.column_name as per your example data, there after you could have two ng-repeat over a data where you will be actually have 1st ng-repeat over tbody & then the another will appear on tr . I'd prefer this approach when I have small data set. For larger data set the answer given by @Tiago is fine.

<table >
    <thead >
        <tr>
            <th ng-repeat="column in entity.columns">{{column.columnName}}</th>
        </tr>
    </thead>
    <tbody ng-repeat="column in entity.columns" >
        <tr ng-repeat="card in column.cards">
            <td >{{card.task}}</td>
        </tr>
    </tbody>
</table>

If you want to stick with creating your own <table> manually, you need to pre-process your data object in order to fit the row logic. Try something like this fiddle :

Add this in your controller:

 $scope.rowColumns = [];
    $scope.columns.forEach(function(column, columnIndex){
        column.cards.forEach(function (card, rowIndex){
            if (!$scope.rowColumns[rowIndex])
                $scope.rowColumns[rowIndex] = [];
            $scope.rowColumns[rowIndex][columnIndex] = card;
        });
    });
    console.log($scope.rowColumns);

Then add this in your html:

   <tr ng-repeat="row in rowColumns">
      <td ng-repeat="cell in row">
           {{cell.task}}
      </td>
   </tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM