AngularJS动态表格,列数未知

13

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

请问您能否展示一下服务器请求的样例结果? - David Frank
当然可以:http://testarium.makseq.com/temp/table1.json 和 http://testarium.makseq.com/temp/table2.json - Max Tkachenko
3个回答

34

您可以基本上使用两个嵌套的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(),例如:<div ng-click="loadNew()"></div>

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


非常感谢!但是我如何通过鼠标点击动态创建表格呢?我需要多个表格(每次点击一个)... - Max Tkachenko
嗨,谢谢。但是如果我需要格式化特定列的数据,比如日期字段,该怎么办? - Nikhil Mahajan
@NikhilMahajan,你可以获取已格式化的数据,或者在loadNew()函数中进行格式化,或者手动重写ng-repeat="column..",按照你想要的方式呈现每列。 - David Frank

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

};

谢谢!如果我需要多个表格,比如每次点击都需要一个新的怎么办? - Max Tkachenko
将ng-repeat添加到表格中:<table ng-repeat="t in tables"></table>,将loadData更改为附加到tables数组,并且每个表格都是包含表格数据的对象。 - benri

1
我有一个列名数组叫做columns,还有一个被称为rows的二维数组。该解决方案适用于任意数量的行和列。在我的示例中,每行都有一个名为“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>

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接