Skaidrius
Skaidrius

Reputation: 131

Dynamic table header with subheaders

How to create (with angular) dynamical table header where header cells should have some subheader cells not equal to header cells?

My table is:

var table = [{
header: "a", 
subheaders: "a1", "a2"
}, { 
header: "b", 
subheaders: "b1", "b2", "b3" 
}]

I try to create such table header (table data will have separate controller):

|a    |b       |
|a1|a2|b1|b2|b3|

I use ng-repeat and everything is ok with headers (when i do <tr ng-repeat="head in table"><th>{{head.header}}</th></tr>), but when I try to do the same with subheaders, ng-repeat repeats whole array of subheaders and I am missing some pseudo element of table or smth...

And I get

|a   |b     |
|a1a2|b1b2b3|

here is my code: http://plnkr.co/edit/pSwjxi2vMN61tevArW4F?p=preview

Upvotes: 1

Views: 2560

Answers (1)

sylwester
sylwester

Reputation: 16498

Please see below:

(function() {

  var table = {
    thead: [{
      header: "A",
      subheaders: [
        "A1",
        "A2"
      ]
    }, {
      header: "B",
      subheaders: [
        "B1",
        "B2",
        "B3"
      ]
    }, {
      header: "C",
      subheaders: [
        "C1",
        "C2",
        "C3"
      ]
    }]
  };

  var app = angular.module("app", []);
  app.controller("Controller", function() {

    var vm = this;
    vm.table = table;
    vm.subArray = [];
    vm.subs = function(table) {

      angular.forEach(vm.table.thead, function(header) {

        angular.forEach(header.subheaders, function(subheader) {

          vm.subArray.push(subheader)


        })


      })


    };

    vm.subs();
  });
})()
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-app="app">
  <div ng-controller="Controller as ctrl">

    <h1>Some table</h1>

    <table class="table table-bordered">
      <thead>
        <tr>
          <th ng-repeat="head in ctrl.table.thead" colspan="{{head.subheaders.length}}">{{head.header}}</th>
        </tr>




        <tr>
          <th ng-repeat="sub in ctrl.subArray">{{sub}}</th>
        </tr>

      </thead>
      <tbody>
        <tr>
          <td ng-repeat="i in [1, 2, 3, 4, 5, 6, 7, 8]">{{i}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Upvotes: 2

Related Questions