我有一个属性指令,它只是将类名添加到应用它的元素上。该属性指令应用于表格单元格 <td>
元素。当我有 transclude: true
在指令定义中,它替换了表格单元格的内容。我不知道为什么。我是第一次遇到这个问题,有人可以帮助我吗?
我的理解是,根据定义,transclude 应该包含已经存在的任何内容,但不确定为什么我会遇到这个问题。有人可以提出解决方案吗?
这是代码,
angular.module('app', []).directive('indicator', function () {
return {
restrict: 'AC',
replace: true,
transclude: true,
link: function ($scope, $elem, $attrs) {
if($attrs.type) {
$elem.addClass('indicator-'+$attrs.type);
}
else {
$elem.addClass('indicator');
}
}
};});
html 中的指令定义看起来像,
<td indicator type="someType">5000</td>
正如我之前提到的,如果我将 transclude 设置为 false,那么它会按预期工作。但是当我将 transclude 设为 true 时,它会添加类并且表格单元格内容消失。
最佳答案
去掉 replace
和 transclude
属性。
您显然不想替换元素和replace
is deprecated无论如何。
你也没有使用 ngTransclude
指令(事实上,你根本没有指令模板)所以没有必要 transclude
。
你可以把整个事情简化为
.directive('indicator', function() {
return {
restrict: 'AC',
link: function(scope, element, attrs) {
element.addClass(attrs.type ? 'indicator-' + attrs.type : 'indicator');
}
};
})
关于javascript - 表格单元格元素中的 Angular 嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276936/