使用ngRepeat的复杂嵌套行表

时间:2016-01-04 14:05:33

标签: javascript angularjs

我有一个看起来像这样的对象:

{
    "10": {},
    "12": {
        "20": {
            "value": 1,
            "id": 1,
        },
        "100": {
            "value": 12,
            "id": 1,
        }
    },
    "14": {
        "100": {
            "value": 14,
            "id": 2,
        }
    },
    "16": {},
    "18": {},
    "20": {
        "100": {
            "value": 23,
            "id": 1,
        },
        "150": {
            "value": 56,
            "id": 3,
        }
    },
    "22": {},
    "24": {},
    "26": {
        "50": {
...

我想基于这个对象创建一个表格,如下所示:

enter image description here

我不知道如何通过使用重复的正确组合来创建此表。我目前正在尝试这个:

<table>
    <thead>
        <tr>
            <th>type</th>
            <th>module</th>
            <th>value</th>
            <th>id</th>
        </tr>
    </thead>
    <tbody>

        <tr ng-repeat-start="(row1, value1) in TestData">
            <td rowspan="{{value1.length}}">{{row1}}</td>
            <td ng-repeat="(label2, value2) in value1">{{label2}}</td>
        </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

乍一看,您可以通过插入<tbody>来执行此类操作(此处提供更多信息:Angular.js ng-repeat across multiple tr's

var myAppModule = angular.module('myApp', []).controller('MyController', MyController);

function MyController() {

  // https://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes
  this.objectCount = function(obj) {
    return Object.keys(obj).length;
  }

  this.data = {
    "10": {},
    "12": {
      "20": {
        "value": 1,
        "id": 1,
      },
      "100": {
        "value": 12,
        "id": 1,
      },
      "200": {
        "value": 120,
        "id": 10,
      }
    },
    "14": {
      "100": {
        "value": 14,
        "id": 2,
      }
    },
    "16": {},
    "18": {},
    "20": {
      "100": {
        "value": 23,
        "id": 1,
      },
      "150": {
        "value": 56,
        "id": 3,
      }
    },
    "22": {},
    "24": {}
  };

}
table,
th,
td {
  border: 1px solid black;
}
table {
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController as ctrl">
  <table>
    <thead>
      <tr>
        <th>type</th>
        <th>module</th>
        <th>value</th>
        <th>id</th>
      </tr>
    </thead>
    <tbody ng-repeat="(row1, value1) in ctrl.data" ng-switch="ctrl.objectCount(value1) === 0">
      <tr ng-switch-when="true">
        <td>{{row1}}</td>
        <td colspan="3"></td>
      </tr>
      <tr ng-switch-when="false" ng-repeat="(row2, value2) in value1">
        <td ng-if="$index === 0" rowspan="{{ctrl.objectCount(value1)}}">
          {{row1}}
        </td>
        <td>{{row2}}</td>
        <td>{{value2.value}}</td>
        <td>{{value2.id}}</td>
      </tr>
    </tbody>
  </table>
</div>

如果你需要通过合并行和列来更精确的东西,你应该考虑构建一个更加面向的视图对象,这样模板就更简单了,你的业务逻辑也是用JavaScript。