1

I have code that generates a description of an HTML table row, like so:

  [
    {element: 'th', content: 'Header 1'},
    {element: 'td', content: 'data 1'},
    {element: 'td', content: 'data 2'},
  ]

I'd like to output these with angularjs, something like

<tr>
  <td ng-repeat="item in row" >{{item.content}}</td>
</tr>

Except I can't figure out how this could handle the element(s) that are supposed to be <th>?

(Vuejs, for example, has <td v-is="item.element">{{item.content}}</td> but I'm working in an angularjs app, so this example is given in case it helps Vuejs people understand what I need.)

artfulrobot
  • 20,637
  • 11
  • 55
  • 81

1 Answers1

0

Thanks to Clint's answer, a variation that works with tables is:

Create a directive that deletes itself (!)

angular.module('theapp').directive('repeatSection', function () {
  return { restrict: 'A', replace: true, link(scope, el) { el.remove(); } };
});

Use <td> elements to wrap the logic:

<table>
 ...
 <tbody>
   <tr ng-repeat="row in rows">

     <td repeat-section ng-repeat-start="cells in row"></td>
     <th ng-if="cell.element === 'th'">{{cell.content}}</th>
     <td ng-if="cell.element === 'td'">{{cell.content}}</td>
     <td repeat-section ng-repeat-end></td>

   </tr>
 </tbody>
</table>
  • the repeat-section directive deletes the td elements that are created as part of the ng-repeat-start.
  • we need to use <td> here - if you use <div> or <repeat-section> even, these elements get emptied (at least in Firefox), since a <tr> can only contain <td> or <th>.
  • this works for my use (table cells), but is not a general solution - as you'll see I've had to include one of each possible element; that would get messy in the general case.
artfulrobot
  • 20,637
  • 11
  • 55
  • 81