Search code examples
javascriptangularjsangularjs-ng-repeatcss-tables

using ng-repeat to build a table


I have a data structure like this:

{
  "Places to visit": {
    "Best": [
      "place1",
      "place2"
    ],
    "Worst": [
      "place3",
      "place4"
    ]
  },
  "Cuisines": {
    "Best": [
      "cuisine1",
      "cuisine2"
    ],
    "Worst": [
      "cuisine3",
      "cuisine4"
    ]
  },
  "Mobiles": {
    "Best": [
      "mobile1",
      "mobile2"
    ],
    "Worst": [
      "mobile3",
      "mobile4"
    ]
  }
}

Using this datastructure, I need to build a table in the UI which should look like this (with 2 indicators in one row). enter image description here

I'm clueless on how to use ng-repeat on this data structure to get the desired table.

TIA.


Solution

  • If you want to use an html table, you'll need to reformat your data and probably want to use ng-repeat-start and ng-repeat-end which allow multiple elements for a single item in your array.

    As an example, a 'row' of data would have a as places to visit and b as cuisines:

    <table>
      <thead>
        <tr>
          <th>&nbsp;</th><th>best</th><th>worst</th><th>&nbsp;</th><th>best</th><th>worst</th>
        </tr>
        </thead>
      <tbody>
        <tr ng-repeat-start="row in vm.rows">
          <td rowspan="2">{{row.a.text}}</td>
          <td>{{row.a.items[0]}}</td>
          <td>{{row.a.items[2]}}</td>
          <td ng-if="row.b" rowspan="2">{{row.b.text}}</td>
          <td ng-if="row.b">{{row.b.items[0]}}</td>
          <td ng-if="row.b">{{row.b.items[2]}}</td>
        </tr>
        <tr ng-repeat-end>
          <td>{{row.a.items[1]}}</td>
          <td>{{row.a.items[3]}}</td>
          <td ng-if="row.b">{{row.b.items[1]}}</td>
          <td ng-if="row.b">{{row.b.items[3]}}</td>
        </tr>
      </tbody>
    </table>
    

    So each element of the 'items' array creates two table rows and contains 'a' and 'b' elements for the side-by-side items.

    codepen