how to add a table row as a template using angular js

十年热恋 提交于 2019-12-08 05:57:54

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/26287410/how-to-add-a-table-row-as-a-template-using-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!