3

I have an attribute directive which just adds a class name to the element on which it is applied. That attribute directive is applied to a table cell <td> element. When I have transclude: true in the directive definition it replaces the table cell content. I cannot figure out why. Can someone help me out since I'm facing this issue for the first time?

My understanding is by definition transclude should contain whatever content was in there already but not sure why I'm facing this issue. Can someone suggest a solution?

Here is the code,

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');    
        }
    }
};});

the directive definition in html would look like,

<td indicator type="someType">5000</td>

As I mentioned earlier if I have transclude as false then it works as expected. But when I have transclude as true it adds the class and the table cell content disappears.

4

1 回答 1

2

摆脱replacetransclude属性。

您显然不想替换该元素,并且无论如何replace都已弃用。

您也没有使用ngTransclude指令(实际上,您根本没有指令模板),因此无需transclude.

您可以将整个事情简化为

.directive('indicator', function() {
    return {
        restrict: 'AC',
        link: function(scope, element, attrs) {
            element.addClass(attrs.type ? 'indicator-' + attrs.type : 'indicator');
        }
    };
})
于 2015-12-14T21:44:22.050 回答