Angular 指令不适用于 table

Angular directive doesn't work on table

我有以下 table:

<table>
  <thead>
    <tr>
      <th>Uno</th>
      <th>Dos</th>
    </tr>
  </thead>

  <!--directive template should be here-->
  <double-rows></double-rows>
  <!--/directive template should be here-->

</table>

指令定义为:

angular.module('app', []);

angular.module('app').directive('doubleRows', function () {
  return {
    templateUrl: 'template.html',
    restrict: 'E',
    scope: {
      row: '='
    }
  }
});

虽然看起来很简单,但无法正确呈现。例如:

<double-rows class="ng-isolate-scope">

Cell1
Cell2

</double-rows>

<table>
  <thead>
    <tr>
      <th>Uno</th>
      <th>Dos</th>
    </tr>
  </thead>

  <!--directive template should be here-->

  <!--/directive template should be here-->

</table>

您可以在此处查看完整代码:https://plnkr.co/edit/0Z65aK?p=preview

如何让它发挥作用?

这不完全是一个 angular 问题,而是与浏览器如何决定解释您编写的 HTML 有关。某些标签不允许嵌套在其他标签中,这在列表(ul 或 li)和 tables(也适用于嵌套链接和其他一些东西)中尤为普遍。

如果您使用 restrict A 并使用 table 中允许的元素类型,而不是使用 restrict E,那么它就可以工作(我还在您的指令中使用了 replace:true,因此它替换了原来的它应用到的元素而不是它的子元素)

https://plnkr.co/edit/fgRzZU?p=preview

angular.module('app').directive('doubleRows', function () {
  return {
    templateUrl: 'template.html',
    restrict: 'A',
    replace:true,
    scope: {
      row: '='
    },
    controller: function () {
      console.log('hi');
    }
  }
});

HTML

<table>
  <thead>
    <tr>
      <th>Uno</th>
      <th>Dos</th>
    </tr>
  </thead>

  <!--directive template should be here-->
  <tbody double-rows>
  </tbody>
  <!--/directive template should be here-->

</table>