1

I would like to add a row dynamically to a table. I would like to reuse the row in a few tables.

I tried doing this with a directive and by using ng-include but neither option worked as I expected.

Basically, this is what I did:

myapp.directive('myRow', function () {
    return {
        restrict : 'E',
        replace : true,
        scope : { mytitle : '@mytitle'},
        template : '<tr><td class="mystyle">{{mytitle}}</td></tr>' 
    }
});

and in html:

<table>
    <tbody>
        <tr><td>data</td></tr>
        <my-row></my-row>
    </tbody>
</table>

The <tr> element gets drawn but ends up outside the <table> element in the dom.

Is there a simple way to include table rows using angularjs?

PSL
  • 123,204
  • 21
  • 253
  • 243
chriskelly
  • 7,526
  • 3
  • 32
  • 50
  • 1
    You have a typo `` it must be `` You cannot have 2 root elements in the template. Just check your console, you will get all kinds of clues there itself. http://plnkr.co/edit/pCNbci?p=preview – PSL Oct 09 '14 at 20:31
  • thanks! I just typed it into SO. Real code is correct. – chriskelly Oct 09 '14 at 20:32
  • That is because browser it throwing it out. you cannot have anything else as a child of tbody. make your directive attribute directive and you should be good to go. Check my demo. – PSL Oct 09 '14 at 20:33
  • 1
    Just check my demo in chrome.. it will be fine – PSL Oct 09 '14 at 20:35

2 Answers2

5

Your issue is that you have invalid html structure because of the presence of the custom element my-row inside tbody. You can only have tr inside tbody. So the browser is throwing your directive element out of the table even before angular has a chance to process it.So when angular processes the directive, it processes the element outside the table.

In order to fix this, change your directive to be attribute restricted directive from element restricted.

   .directive('myRow', function () {
     return {
        restrict : 'A',
        replace : true,
        scope : { mytitle : '@mytitle'},
        template : '<tr><td class="mystyle">{{mytitle}}<td></tr>' 
     }

and use it as:-

  <table>
    <tbody>
        <tr><td>data</td></tr>
        <tr my-row mytitle="Hello I am Title"></tr>
    </tbody>
  </table>

Plnkr

Community
  • 1
  • 1
PSL
  • 123,204
  • 21
  • 253
  • 243
0

Correct if I am wrong but this approach does not work if someone wants to insert two or more rows replacing the current row. Following thread addresses this issue by replacing the tr withing link function.

AngularJs while replacing the table row - changing html from compile function but scope is not getting linked

Community
  • 1
  • 1
Yogesh Manware
  • 1,843
  • 1
  • 22
  • 25