javascript - 如何在 Angular Directive(指令)(transclude)中包含 <tr> 元素?

标签 javascript html angularjs

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

<my-table>
   <tr>
     <td>hello</td>
     <td>world</td>
   </tr>
</my-table>

这是javascript:

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

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

我的表格.html :

<table ng-transclude>

</table>

上面的代码导致:

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

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

</table></my-table>

示例:PLUNKR

最佳答案

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

  <my-table>
  <table>
      <tr>
       <td>hello</td>
       <td>world</td>
     </tr>
  </table>
  </my-table>

然后您将能够访问 tbody由浏览器创建的元素以及 tr在链接函数中并处理它:

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

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

关于javascript - 如何在 Angular Directive(指令)(transclude)中包含 <tr> 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40779243/

相关文章:

angularjs - 更改我的项目文件不会更改 Docker 机器内的文件

javascript - Require.js 加载应用程序的所有资源,包括 Polymer

javascript - 使用 javascript/jQuery 获取样式表中的 CSS 类列表

AngularJS 验证 ngModel 未定义

JavaScript 将数组推送到类原型(prototype)问题

javascript - 将 jQuery 函数作为字符串传递

javascript - 状态变量的变化不可预测 - ReactJS

javascript - d3js - 创建自定义比例 - 正对数和负对数

javascript - JS 获取带有表格内容的 HTML `<template>` innerHTML 失败

html - 如何为这些绝对定位的 <a> 元素应用边距?