テーブルとデータ
これは何か
データテーブルを表示する場合、どのようなデータの型が利用しやすいか、について整理してみました。
参考にしたのは以下2つのライブラリ
例
以下のようなテーブルを表示したい。
ID | Date | Name | Age |
---|---|---|---|
1 | March 5, 2017 | Foo | 26 |
2 | March 6, 2017 | Bar | 31 |
データのみ用意
配列
const data = [ [1, 'March 5, 2017', 'Foo', 26], [2, 'March 6, 2017', 'Bar', 31] ];
- 一番シンプル
- カラムタイトルなどは別途用意する必要がある(Htmlのテンプレート内など)
オブジェクト
const data = [ { id: 1, date: 'March 5, 2017', name: 'foo', age: 26}, { id: 2, date: 'March 6, 2017', name: 'bar', age: 31}, ];
- 1行目を利用して、カラムタイトルを作成
- オブジェクトだからカラム項目の順番は保証できないはず
データとカラム用の設定データ
- 汎用性が高いのはこっち
配列
const data = [ [1, 'March 5, 2017', 'Foo', 26], [2, 'March 6, 2017', 'Bar', 31] ]; const columns = [ { name: 'ID'}, { name: 'Date'}, { name: 'Name'}, { name: 'Age'} ];
オブジェクト
const data = [ { id: 1, date: 'March 5, 2017', name: 'foo', age: 26}, { id: 2, date: 'March 6, 2017', name: 'bar', age: 31}, ]; const columns = [ { field: 'id', name: 'ID' }, { field: 'date', name: 'Date' }, { field: 'name', name: 'Name' }, { field: 'age', name: 'Age' } ];
- カラムタイトル(name)とプロパティ名(field)を別にできる
const data = [ { id: 1, date: 'March 5, 2017', customer: { name: 'foo', age: 26 } }, { id: 2, date: 'March 6, 2017', customer: { name: 'bar', age: 31} }, ]; const columns = [ { field: 'id', name: 'ID' }, { field: 'date', name: 'Date' }, { field: 'customer.name', name: 'Name' }, { field: 'customer.age', name: 'Age' } ];
- データのネストなども対応可能
複雑なテーブル
カラム設定データを用意する場合、以下の機能の実現も汎用的にできそう。
- ソート機能のオンオフ
- 合計値の表示
- 平均値の表示
- データと表示内容の変更
2017-03-05
->March 5, 2017
or2017年3月5日
UI-Gridだとこのような感じで設定を追加しています。
// http://ui-grid.info/docs/#/tutorial/105_footer $scope.gridOptions = { showGridFooter: true, showColumnFooter: true, enableFiltering: true, columnDefs: [ { field: 'name', width: '13%' }, { field: 'address.street',aggregationType: uiGridConstants.aggregationTypes.sum, width: '13%' }, { field: 'age', aggregationType: uiGridConstants.aggregationTypes.avg, aggregationHideLabel: true, width: '13%' }, { name: 'ageMin', field: 'age', aggregationType: uiGridConstants.aggregationTypes.min, width: '13%', displayName: 'Age for min' }, { name: 'ageMax', field: 'age', aggregationType: uiGridConstants.aggregationTypes.max, width: '13%', displayName: 'Age for max' }, { name: 'customCellTemplate', field: 'age', width: '14%', footerCellTemplate: '<div class="ui-grid-cell-contents" style="background-color: Red;color: White">custom template</div>' }, { name: 'registered', field: 'registered', width: '20%', cellFilter: 'date', footerCellFilter: 'date', aggregationType: uiGridConstants.aggregationTypes.max } ], data: data, onRegisterApi: function(gridApi) { $scope.gridApi = gridApi; } };