Chuck Villavicencio
Chuck Villavicencio

Reputation: 393

Create table with two (or more) columns, each one with different ng-repeat

I need to buid a table with 'n' number of columns. Every column will be feeding with the info from different arrays.

Per example, let's say i have the next arrays:

$scope.first = [1, 4, 7];
$scope.second = [2, 5, 8];
$scope.third = [3, 6, 9];

And my goal is to show the info as three (or 'n') columns:

<table align="center">
    <thead>
    <tr>
        <th colspan="3" scope="colgroup">Data</span></th>
    </tr>
    </thead>
    <tbody>
        <th>First</th>
        <th>Second/th>
         <th>Third</th>
</tbody>

The problem comes when i'm triying to pass every array on the ng-repeat. What can i do to show my info as i want? If i pass the ng-repeat on another <tbody> the data will appear as a column of the First <th>, but it breaks everything when i'm triying to pass the Second and Third array.

I need to show it almost as a calendar:

enter image description here

Someone can help me, please?

I'm using AngularJS and Javascript.

Upvotes: 0

Views: 382

Answers (2)

Icycool
Icycool

Reputation: 7179

It is easier to represent the whole thing using a single structure

$scope.data = [
  {name: "First", values: [1,4,7]},
  {name: "Second", values: [2,5,8]},
  {name: "Third", values: [3,6,9]},
]

// get max length of all arrays here, do it by code
$scope.maxRow = new Array(3); 

<table align="center">
    <thead>
    <tr>
        <th colspan="3" scope="colgroup">Data</span></th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <th ng-repeat="column in data">{{column.name}}</th>
    </tr>
    <tr ng-repeat="row in maxRow">
        <td ng-repeat="col in data">{{col.length > row ? col.values[row] : '-'}}</td>
    </tr>
    </tbody>
</table>

Upvotes: 1

Amir Mohammad Moradi
Amir Mohammad Moradi

Reputation: 887

use this type of representation to support even n columns:

your arrays :

$scope.myArrays = [[1, 4, 7],[2, 5, 8],...,[3, 6, 9]]

your table :

<table style="width:100%">
  <tr>
    <th colspan="{{myArrays.length}}" scope="colgroup">Data</th>
  </tr>
  <tr ng-repeat="array in myArrays">
    <td ng-repeat="item in array track by $index">{{item}}</td>
  </tr>
</table>

UPDATE

to show vertical, change the arrays like this :

var myArrays =[[1, 4, 7],[2, 5, 8],[3, 6, 9]];
var _newArray = [];

for(var i=0; i<myArrays.length ;i++){
     _newArray[i] = [];
   for(var j=0; j<myArrays.length ;j++){
     _newArray[i].push(myArrays[j][i]);
  }
}

$scope.myArrays = _newArray

this works for n-x.n and n.n arrays

Upvotes: 1

Related Questions