AngularJS ng-repeat动态行跨

时间:2017-02-02 00:42:39

标签: angularjs

我有一些数据数组,如:

arr = [

{"name": "John", "age": 17, "brothers":[{"name":"steve"},{"name":"james"},"name":"robert","name":"juzu"],
{"name": "Doe", "age": 18, "brothers":[{"name":"kelly"},{"name":"smith"}, "name":"herry"],
{"name": "John Doe", "age": 19, "brothers":[{"name":"old"},{"name":"sch"}, {"name":"Jee"},{"name":"hero"},{"name":"tony"}],

];

我想创建像:

这样的表格

LIKE THIS

但是,我的td显示了brothers.name限制为2。 如果我的borthers.name数据> 2,我的arr.name rowspan添加+1

1 个答案:

答案 0 :(得分:1)

如果不对数据进行任何修改,您可以使用数学运算,但尝试其他方式显示数据,如每个父数据的模态或内部表格

<强> HTML

<div ng-controller="MyCtrl">
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th colspan="2">Brothers</th>
            </tr>
        </thead>
        <tbody>
            <tr style="display: none"  ng-repeat-start="(k1, v1) in data"></tr>
            <tr>
                <td rowspan="{{ Math.ceil(v1.brothers.length/2) }}">{{v1.name}}</td>
                <td>{{v1.brothers[0].name  }}</td>
                <td>{{v1.brothers[1].name  }}</td>
            </tr>
            <tr ng-repeat="(k2, v2) in calcData(v1.brothers)">
                <td>{{v1.brothers[v2].name || '' }}</td>
                <td>{{v1.brothers[v2+1].name || ''}}</td>
            </tr>
            <tr style="display: none" ng-repeat-end></tr>
        </tbody>
    </table>
</div>

<强>的JavaScript

angular.module('App', []);
angular.module('App').controller('MyCtrl', function($scope) {
    $scope.Math = window.Math;
    $scope.data = [{
        "name": "John",
        "age": 17,
        "brothers": [{ "name": "steve" }, { "name": "james" }, { "name": "robert" }, { "name": "juzu" }]
    }, {
        "name": "Doe",
        "age": 18,
        "brothers": [{ "name": "kelly" }, { "name": "smith" }, { "name": "herry" }]
    }, {
        "name": "John Doe",
        "age": 19,
        "brothers": [{ "name": "old" }, { "name": "sch" }, { "name": "Jee" }, { "name": "hero" }, { "name": "tony" }]
    }
    ];
    $scope.calcData = function (data) {
        var tempData = angular.copy(data);
        var temp = [];
        for (var i = 0; i <= Math.ceil(tempData.slice(2, data.length).length/2); i++) {
            if (i%2==0) {
                temp.push(i+2)
            }
        }
        return temp;
    }
});

<强>输出

enter image description here