AngularJS: how to build an HTML table with data multiple-levels deep?

前端 未结 1 762
无人及你
无人及你 2021-01-16 05:16

I need to create a table from some data with multiple levels of arrays and sub-arrays. I have found some solutions to do this as long as I only have two levels of arrays, bu

相关标签:
1条回答
  • 2021-01-16 06:12

    After much frustration and head scratching, I found a way to do it using ng-repeat-start

    <table>
        <tbody>
            <tr ng-repeat-start="p in professors" ng-if="false"></tr>
            <tr ng-repeat-start="c in p.classes" ng-if="false"></tr>
            <tr ng-repeat="s in c.students">
                <th ng-if="$parent.$first && $first" rowspan="{{p.count}}">
                    {{p.name}}
                </th>
                <th ng-if="$first" rowspan="{{c.students.length}}">{{c.name}}</th>
                <td>{{s.name}}</td>
                <td>{{s.grade}}</td>
            </tr>
            <tr ng-repeat-end ng-if="false"></tr> <!-- classes -->
            <tr ng-repeat-end ng-if="false"></tr> <!-- professors -->
        </tbody>
    </table>
    

    This solution generates valid HTML table markup. By using ng-if="false" on the ng-repeat-* elements, they iterate through the arrays but generate no actual element on the page. The only elements generated are the tr rows in s in c.students.

    The other thing I needed to do is create a new property inside the professor objects named count that holds the total number of students enrolled in all the classes. I needed that for the rowspan and it's of course trivial to generate on the fly when I get data from the server.

    0 讨论(0)
提交回复
热议问题