Angular 嵌入 table 单元格元素

Angular transclude in table cell element

我有一个属性指令,它只向应用它的元素添加一个 class 名称。该属性指令应用于 table 单元格 <td> 元素。当我在指令定义中有 transclude: true 时,它会替换 table 单元格内容。我不知道为什么。我是第一次遇到这个问题,有人可以帮助我吗?

我的理解是,根据定义,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 时,它​​会添加 class 并且 table 单元格内容消失。

删除 replacetransclude 属性。

您显然不想 替换 元素和 replace is deprecated 无论如何。

你也没有使用 ngTransclude 指令(事实上,你根本没有指令模板)所以没有必要 transclude.

你可以将整个事情简化为

.directive('indicator', function() {
    return {
        restrict: 'AC',
        link: function(scope, element, attrs) {
            element.addClass(attrs.type ? 'indicator-' + attrs.type : 'indicator');
        }
    };
})