如何使用angular js将表格行添加为模板 [英] how to add a table row as a template using angular js

查看:80
本文介绍了如何使用angular js将表格行添加为模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向表中动态添加一行.我想在几张表中重复使用该行.

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

我尝试使用指令并通过使用ng-include来执行此操作,但没有一个选项能按预期工作.

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>' 
    }
});

和html中的

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

<tr>元素被绘制但在dom中<table>元素的 outside 之外结束.

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

有没有一种简单的方法可以使用angularjs包含表格行?

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

推荐答案

您的问题是,由于tbody中存在自定义元素my-row,因此您的HTML结构无效. tbody内只能包含tr.因此,即使在angular没有机会对其进行处理之前,浏览器也会将您的指令元素从表中抛出.因此,当angular处理该指令时,它将在表外处理该元素.

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>' 
     }

并将其用作:-

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

Plnkr

Plnkr

这篇关于如何使用angular js将表格行添加为模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆