【发布时间】:2016-08-22 09:35:13
【问题描述】:
我已经使用 AngularJS 工作了几个月。今天,我需要创建一个指令来帮助我将修复标题添加到表中。我发现的所有指令都不够好,因为它们处理列大小的方式(我仍然愿意接受建议)。
我们使用 jQuery 制作的“旧”函数,我正在尝试将其转换为指令。目标是克隆表(或表头)并处理隐藏/显示函数及其位置以获得良好的结果。
我的问题:我的表的标题是动态的,带有生成的列:
<table>
<thead>
<tr>
<th></th> // true th elements, used for styling my table
<th></th>
<th class='text-center' ng-repeat="thing in things">
{{thing.label}}
</th>
</tr>
</thead>
<tbody>
// my tbody
</tbody>
</table>
我正在尝试使用类似的方式在我的指令中获取 <th> 元素:
angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) {
console.log(thElem)
// do stuff here
}
});
但我只得到了前两个<th>,它们是我的代码中的“真实”元素。由 ng-repeat 生成的所有其他内容都将被忽略。或者没有注入到我的指令中。
我查看了 transclude 属性,但找不到任何有效的方法。你能帮我精确一下吗?
编辑:这是我的指令的开头:
myApp.directive('fixMe', function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
angular.forEach(element.querySelectorAll('th'), function (thElem, i) {
console.log(thElem);
var columnWidth = thElem.offsetWidth;
thElem.style.width = columnWidth + 'px';
});
}
};
})
【问题讨论】:
-
我不确定我是否理解 - 你想把
<thead>中的所有内容都放入指令中吗?你不能把代码放在指令模板中吗? -
我的目标是有一个适用于任何表的指令(无论行数、列数等)。我可以用模板做到这一点吗?
标签: javascript jquery angularjs html-table directive