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

查看:25
本文介绍了如何使用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 中的

元素之外.

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?

推荐答案

您的问题是您的 html 结构无效,因为 tbody<中存在自定义元素 my-row/代码>.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

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

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