首页 > 解决方案 > 如何使用具有动态列数和行数的 CSS 网格?

问题描述

我正在尝试在 Angular 中创建一个具有动态列数和行数的表。通过执行以下操作,我发现使用 HTML 表格元素很容易实现这一点:

    <table class="html-table">
      <tr class="headers">
        <th>Name</th>
        <th>Age</th>
        <th>Sex</th>
        <th *ngIf="columns == 4">Species</th>
      </tr>
      <tr>
        <td>Ryan</td>
        <td>30</td>
        <td>M</td>
        <td *ngIf="columns == 4">Human</td>
      </tr>
    </table>

在此示例中,可能有一些按钮可以切换 和之间columns的值。34

我在网上看到的每一个解释都涉及更改 CSS 变量,这似乎是一种完成本应简单的事情的有点笨拙的方法。有什么方法可以指定应该是 CSS 网格中的新列,而不是必须指定列数grid-template-columns吗?

标签: htmlcsshtml-tableflexboxcss-grid

解决方案


在 Angular 中,您可以使用ng-repeat动态表

一个典型的例子可能是

<table ng-table="tableParams" class="table table-striped">
   <tr ng-repeat="data in datas">
      <td title="Title_Of_First_Variable">{{data.variable1}}</td>
      <td title="Title_Of_Second_Variable">{{data.variable2}}</td>
      <td title="Title_Of_Third_Variable">{{data.variable3}}</td>
      ...
   </tr>
</table>

当然,使用您的控制器,您应该将动态数据传递到正确的 $scope,在这种情况下应该是 $scope.datas(通常是一个对象)......可能是这样的,使用 NodeJS:

$http.post('route_of_your_method')
.success(function (result) {
     $scope.datas = result;      
})
.error(function (err) {
     ...
});

我解释得很快,但我希望这已经足够了


推荐阅读