phillydigital phillydigital - 4 months ago 86x
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


function Ctrl($scope) {
$ = [];
$[3] = [];
$[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 = $;


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



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


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


  // 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
  $ = // row data arrays

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