phillydigital phillydigital - 6 months ago 133
AngularJS Question

Add table columns dynamically with Angular.js

I'm trying to use Angular.JS to dynamically add columns to an html table.

It starts with a set of data, and I want to make extra data available on a click. I'm new to Angular, and made this plunker to illustrate what I'm trying to do. I'd like to (obviously) just add a new table header and a new table data based on the number of items in the array, matched to the index number of the same row. Thank you

Controller:

function Ctrl($scope) {
$scope.data = [];
$scope.data[3] = [];
$scope.data[0] = [['New York', 1000,2000],['Los Angeles', 200,400],['Nottingham', 800,400]]
$scope.moredata = [1500, 2500, 4500];
temp = []
$scope.getData = function() {
$scope.moduleArray[1] = $scope.moredata;
}
$scope.moduleArray = $scope.data;
}


HTML:

<div ng-controller="Ctrl">
<button ng-click="getData()">Get more data</button>
<table>
<tr>
<th>Location</th>
<th>Current Data</th>
<th ng-repeat="ba in moduleArray[1]">new data</th>
</tr>
<tr data-ng-repeat="item2 in moduleArray[0]">
<td>2[0]{{item2[0]}}</td>
<td>2[1]{{item2[1]}}</td>
<td data-ng-repeat="bat in moduleArray[1]">{{bat[$parent.$index]}}</td>
</tr>
</table>


Plunkr

Answer

Here's very simple set up that toggles single columns on right side.

There are 2 sets of arrays, one for column headers and one for row data. It uses limitTo filter for ng-repeat.

From there it is a simple increment/decrement of a scope variable colCount to add/remove column

View

  <button ng-click="increment('up')">Add Column</button>
  <button ng-click="increment('down')">Remove Column</button>
  <table class="table table-bordered">
    <tr>
      <th ng-repeat="col in cols | limitTo: colCount">{{col}}</th>
    </tr>
    <tr ng-repeat="row in data">
      <td ng-repeat="item in row | limitTo: colCount">{{item}}</td>
    </tr>
  </table>

Controller

  // used as limit for ng-repeat limitTo
  $scope.colCount = 3;

  $scope.increment = function(dir) {
    (dir === 'up') ? $scope.colCount++: $scope.colCount--;
  }

  $scope.cols = // array of column names
  $scope.data = // row data arrays

Note that for large tables this may not great for performance due to multiple nested repeaters

DEMO