angularjs - 作为指令的表行在 angularjs 中显示在表上下文之外

标签 angularjs angularjs-directive

我有一个表格,每一行都使用指令和 ng-repeat 显示。

不幸的是,这些行是在表上下文之外呈现的。

请在这里运行 fiddle :http://jsfiddle.net/nu1tu9qL/4/

指令:

.directive('myrow', [function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                rowdata: "="
            },
            template: '<tr><td>{{rowdata.a}}</td><td>{{rowdata.b}}</td></tr>',
        };
    }]);

HTML:

<table>
    <thead>
        <th>A</th>
        <th>B</th>
    </thead>
    <tbody>
        <myrow ng-repeat="d in data" rowdata="d"></row>
    </tbody>
</table>

最佳答案

如果不深入 Angular 的源代码来诊断这个问题,我会说这很可能是您在 <tbody> 中使用了意外元素这一事实的产物。 . <tbody> accepts only <tr> (为了这个问题的目的)。

因此,更改您的 myrow指令是一个属性,并使模板只添加 <td>小号:

<tbody>
  <tr myrow rowdata="d" ng-repeat="d in data"></tr>
</tbody>

和指令:

.directive("myrow", function(){
  return {
    scope: {
      rowdata: "=?"
    },
    template: "<td>{{rowdata.a}}</td><td>{{rowdata.b}}</td>"
  };
});

(您甚至可以使用 myrow 作为范围,而不是 rowdata )

编辑:

为了验证上述假设,我reproduced具有以下行为:

<table>
  <tr><th>Column 1</th></tr>
  <tbody>
    <myrow></myrow>
  </tbody>
</table>

并使用 jQuery(类似于 Angular 会做的事情):

$(function(){
    $("myrow").replaceWith("<tr><td>A</td></tr>");
});

结果是插入的行出现在<table>上面,就像原始问题中的情况一样。事实上,<myrow>甚至在 replaceWith 之前就被移出了表格(在 Chrome 和 IE 中——不确定这是否是特定于浏览器的行为)发生了。

关于angularjs - 作为指令的表行在 angularjs 中显示在表上下文之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28672550/

相关文章:

angularjs - 如何在Angular JS中进行图像分析?

javascript - Angular 指令限制 E 破坏代码

javascript - 在 ng-switch 中使用 ng-transclude

Angularjs:查找指令的所有实例

angularjs - 触发除按键或按键之外的文本框的 ng-change 事件

javascript - 工厂未在 Angular JS 中定义

javascript - 使用 angularJS .component() 但没有得到任何值

javascript - 尝试在范围隔离指令中运行绑定(bind)方法

javascript - AngularJs 范围变量不起作用

javascript - 如何让 AngularJS 的两个页面共享同一个 $scope?