Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dynamic table with unknown number of columns

I'm new to Angular and I need some start point for my project. How can I create new table from ajax data by mouse click on the background? I know that ajax data has unknown number of columns and can be different from time to time.

For example:

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 |
like image 537
Max Tkachenko Avatar asked Jan 08 '15 23:01

Max Tkachenko


1 Answers

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/

like image 56
David Frank Avatar answered Sep 17 '22 17:09

David Frank