我想包括 <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/