如何在角度指令(transclude)中包含 <tr> 元素?

Den*_*Hiu 5 html javascript angularjs

我想包括<tr>并且<td>显然我不能用指令来做到这一点。它一直忽略<td><td>好像它们不存在。这是我想要完成的:

<my-table>
   <tr>
     <td>hello</td>
     <td>world</td>
   </tr>
</my-table>
Run Code Online (Sandbox Code Playgroud)

这是javascript:

angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {

}])
.directive('myTable', function() {
   return {
     restrict: 'E',
     transclude: true,
     templateUrl: 'my-table.html'
   };
});
Run Code Online (Sandbox Code Playgroud)

我的表.html:

<table ng-transclude>

</table>
Run Code Online (Sandbox Code Playgroud)

上面的代码导致:

<my-table class="ng-isolate-scope"><table ng-transclude="">

   hello  <-- no <tr> nor <td> here just plain text
   world

</table></my-table>
Run Code Online (Sandbox Code Playgroud)

示例:PLUNKR

Max*_*kyi 1

这不是一个嵌入问题。这是无效html的问题,因为<tr>没有表格是无效的。所以 Angular 从浏览器获取text,而不是 DOM 元素。所以你需要<table>在 html 中添加标签:

  <my-table>
  <table>
      <tr>
       <td>hello</td>
       <td>world</td>
     </tr>
  </table>
  </my-table>
Run Code Online (Sandbox Code Playgroud)

然后,您将能够访问tbody浏览器创建的元素以及tr链接函数中的 s 并对其进行处理:

  link: function(scope,element,attrs,ctrls,transclude) {
    var html = transclude();
    element.find('table').append(html[1].firstElementChild);
  }
Run Code Online (Sandbox Code Playgroud)

ng-transclude或像您一样在模板中使用。但是,我可能认为您稍后会想要重用嵌入的部分,因此在链接函数中访问它对我来说更有意义。