使用不一致的列数据构建 table

Build table with inconsistent column data

我需要使用 angular 在不同行的列单元格数量不一致的数据上构建 HTML table。我需要为任何特定行中列数较少的列显示阴影单元格。例如-

数据:

a,b,c,d
1,2,3
4,5,6,7
8,9,10,11,12

预期输出:

是否可以使用 ng-repeat 或其他方式实现此行为?

您可以找到最大的项目集合,然后循环创建 tds。以下是一个工作示例,阅读代码注释以了解其工作原理:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    // The original data
    let data = 'a,b,c,d\n1,2,3\n4,5,6,7\n8,9,10,11,12';

    // Create arrays out of the original data. This will be used to render the table
    $scope.data = data.split('\n')
      .map(item => item.split(','));

    // Find the maximum number of elements so that we can create that much td elements
    $scope.max = Math.max(...$scope.data.map(item => item.length));

    // Helper function to create an array out of given length
    $scope.getArray = length => new Array(length);
  });
td {
  border: 1px solid black;
  width: 50px;
}

.blank {
  background-color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <table>
    <!--Loop over the rows of data-->
    <tr ng-repeat="row in data">
      <!--Loop over an empty array-->
      <td ng-repeat="_ in getArray(max) track by $index" ng-class="{blank: !row[$index]}">
        {{row[$index]}}
      </td>
    </tr>
  </table>
</div>

为了使不可用的项目变灰,它使用 ng-class 指令将 blank class 分配给 td,然后使用 CSS 对其进行着色].