【问题标题】:Table with different number of rows per column using ng-repeat使用 ng-repeat 每列具有不同行数的表
【发布时间】:2014-11-03 09:02:15
【问题描述】:

在我的控制器中,我有一个数据结构:

this.people = [
    {name: person1, spent: [1, 3, 5,...]},
    {name: person2, spent: [4, 57, 3,...]},
    ...
];

我想以某种方式将该数据提取到一个类似表格的结构中,名称是列,所用表格的元素是相应列的行(其中每个人的列可以具有不同的长度):

person1 | person2
1       | 4
3       | 57
5       | 3

我可以用 AngularJS 和 ng-repeat 以某种方式做到这一点吗?或者以任何其他方式不会迫使我明确地循环遍历每个人的“花费”元素?

【问题讨论】:

  • 每个人花费的数组长度是否相等?
  • 不,数组可能有不同的长度,我发现这是最有问题的部分

标签: html angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

对于更标准的解决方案,您需要知道已用数组的最大长度是多少。

我提议:

$scope.maxSpent = function(){
    var max = [];
    for (var i in $scope.people){
        var p = $scope.people[i];
        if (p.spent.length > max.length){
            max = p.spent;
        }
    }
    return max;
}

这将经常被重新计算,您可能会更聪明,具体取决于您获取人员数组的方式。

完成后,您可以构建您想要的表格:

<table>
    <tr>
        <td ng-repeat="person in people">{{person.name}}</td>
    </tr>
    <tr ng-repeat="n in maxSpent()" ng-init="count = $index">
        <td ng-repeat="person in people">{{person.spent[count]}}</td>
    </tr>
</table>

Nota-Bene,在上述解决方案中,您可以构建将出现在结果表上的空 TD,由您决定不显示它们:

<table>
    <tr>
        <td ng-repeat="person in people">{{person.name}}</td>
    </tr>
    <tr ng-repeat="n in maxSpent()" ng-init="count = $index">
        <td ng-repeat="person in people" ng-if="person.spent[count]">{{person.spent[count]}}</td>
    </tr>
</table>

【讨论】:

    【解决方案2】:

    以正常方式构建您的数组:

    <table>
        <tr ng-repeat="person in people">
            <td>{{person.name}}</td>
            <td ng-repeat="n in person.spent">{{n}}</td>
        </tr>
    </table>
    

    在你的 CSS 中:

    tr { display: block; float: left; }
    th, td { display: block;}
    

    在控制器中包含您的人员列表:

    $scope.people = [
        {name: "person1", spent: [1, 3, 5]},
        {name: "person2", spent: [4, 57, 3,12]}
    ];
    

    这很神奇,来自here

    【讨论】:

    • 那么的内容呢?如果我把 {{n}} 放在那里,那么我会为每个人连续获得 person.spent 的元素,那么你能指出它应该具有哪些内容来呈现我想要的内容吗?
    • CSS 是这个答案的关键
    • 我很抱歉,错误的复制过去。这应该更好(不适用于 IE ...)
    • 好的,这个解决方案有效,但我感觉它有点像 hack,不允许我进一步玩表的样式(例如应用引导类表-striped 导致垂直条纹,而不是水平条纹;此外,如果我使用引导表类,列不会填满整个表)......所以我仍然怀疑它是否真的是“正确”的做法它。
    • 当然这是一个 hack,但请记住 TR = 表行,然后期望它表现为列是困难的。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签