【问题标题】:AngularJS dynamic table with unknown number of columns具有未知列数的AngularJS动态表
【发布时间】:2015-03-07 05:42:56
【问题描述】:

我是 Angular 新手,我的项目需要一些起点。 如何通过鼠标单击背景从 ajax 数据创建新表? 我知道 ajax 数据的列数未知,并且有时会有所不同。

例如:

the first click on background = table 1, ajax request to /api/table
| A | B | C |
| 1 | 2 | 3 |
| 5 | 7 | 9 |

the second click on background = table 2 and server returns new data from the same url /api/table
| X | Y |
| 5 | 3 |
| 8 | 9 |

【问题讨论】:

标签: angularjs dynamic tabular


【解决方案1】:

您基本上可以通过以下方式使用两个嵌套的 ng-repeats:

<table border="1" ng-repeat="table in tables">
  <tr>
      <th ng-repeat="column in table.cols">{{column}}</th>
  </tr>
  <tr ng-repeat="row in table.rows">
    <td ng-repeat="column in table.cols">{{row[column]}}</td>
  </tr>
</table>

在控制器中:

function MyCtrl($scope, $http) {
    $scope.index = 0;
    $scope.tables = [];
    $scope.loadNew = function() {
        $http.get(/*url*/).success(function(result) {
            $scope.tables.push({rows: result, cols: Object.keys(result)});
        });
        $scope.index++;
    }
}

然后在某处调用 loadNew(),例如。 &lt;div ng-click="loadNew()"&gt;&lt;/div&gt;

示例: http://jsfiddle.net/v6ruo7mj/1/

【讨论】:

  • 非常感谢!但是如何通过鼠标单击动态创建表格?我需要多个表格(每次点击一个)...
  • 嗨。谢谢你。但是,如果我必须格式化特定列(如日期字段)的数据怎么办。帽子怎么做?
  • @NikhilMahajan 您可以检索已经格式化的数据,或者在 loadNew() 函数中对其进行格式化,或者手动重写 ng-repeat="column..",按照您的意愿呈现每一列。跨度>
【解决方案2】:

在背景元素上注册 ng-click 指令以通过 ajax 加载数据, 并使用 ng-repeat 显示不确定长度的数据

<div ng-click="loadData()">
    <table ng-repeat="t in tables">
        <tr ng-repeat="row in t.data.rows">
            <td ng-repeat="col in row.cols">
                {{col.data}}
            </td>
        </tr>
    </table>
</div>

在控制器中:

$scope.tables = [];

$scope.loadData = function() {
    // ajax call .... load into $scope.data

    $.ajax( url, {
        // settings..
    }).done(function(ajax_data){
        $scope.tables.push({
            data: ajax_data
        });
    });

};

【讨论】:

  • 谢谢!如果我需要多个表格怎么办:每次点击一个新表格?
  • 将 ng-repeat 添加到表中:&lt;table ng-repeat="t in tables"&gt;&lt;/table&gt;,将 loadData 更改为追加到表数组,每个表都是一个包含表数据的对象。 (编辑答案)
【解决方案3】:

我有一个名为列的列名数组和一个名为行的二维行数组。此解决方案适用于任意数量的行和列。在我的示例中,每一行都有一个名为“item”的元素,其中包含数据。需要注意的是,列数等于我们要显示的每行的项目数。

<thead> 
    <tr>
        <th ng-repeat="column in columns">{{column}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="row in rows">
        <td ng-repeat="column in columns track by $index"> {{row.item[$index]}} </td>
    </tr>
</tbody>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 2016-04-06
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2015-03-24
    相关资源
    最近更新 更多