AngularJS dynamic table with unknown number of columns

牧云@^-^@ 提交于 2019-11-28 08:28:29

You could basically use two nested ng-repeats in the following way:

<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>

In the controller:

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++;
    }
}

Then call loadNew() somewhere, eg. <div ng-click="loadNew()"></div>

Example: http://jsfiddle.net/v6ruo7mj/1/

register the ng-click directive on your background element to load data via ajax, and use ng-repeat to display data of uncertain length

<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>

in the controller:

$scope.tables = [];

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

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

};

I have an array of column names named columns and a 2D array of rows called rows. This solution works with an arbitrary number of rows and columns. In my example each row has an element called 'item' which contains the data. It is important to note that the number of columns is equal to the number of items per row we want to display.

<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>

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!