0

If I have a directive that has transcluded content passed to it:

<my-dir>
    <div class="content"></div>
</my-dir>

and the directive has its own template:

<div>
    <div class="transcluded-content"></div>
    <button type="button" class="extra-content"></button>
</div>

So how do I transclude the content, but then apply an angular attribute afterwards to that transcluded content so that I will end up with:

<my-dir>
    <div class="transcluded-content">
        <div class="content" ng-style="{'color':'red'}"></div>
    </div>
    <button type="button" class="extra-content"></button>
</my-dir>

As you can see, style color:red has been applied to the transcluded content. Each time I add the ng-style in the compile function, then angular ignores it, and doesn't process it as an attribute, so no style="color:red" is added by angular to that element.

Edit: ngAttribute compiling, but controller running twice

I still have a problem. I needed the $compile within the post link function, but now all functions on my controller run twice when clicked. I assume the directive is being compiled twice?

compile: function compile(tElement, tAttrs) {
    return function (scope, element, attrs, controllers, transclude) {
        transclude(function (clone) {
            element[0].getElementsByClassName('multi-carousel-inner')[0].append(clone[1]);
            var $item = element[0].getElementsByClassName("content")[0];
            $item.setAttribute('ng-style', "{'color':'red'}");
        });
        $compile(element.contents())(scope);
    }
}

Edit 2:

I think this works. From:

Angularjs directive $compile causing ng-click to fire twice

I have just compiled the element again

transclude(function (clone) {
    element[0].getElementsByClassName('transcluded-content')[0].append(clone[1]);
    var $item = element[0].getElementsByClassName("content")[0];
    $item.setAttribute('ng-style', "{'color':'red'}");
    $compile($item)(scope);
});
Community
  • 1
  • 1
tic
  • 2,484
  • 1
  • 21
  • 33
  • I think what you need is to compile the content manually, take a look at https://www.bennadel.com/blog/2748-compiling-transcluded-content-in-angularjs-directives.htm – Yaser Feb 22 '17 at 20:51
  • I was looking at that link, but it doesn't appear to recompile. You can add content, as it is appending elements, but ngAttributes aren't recognized – tic Feb 22 '17 at 20:57
  • can't you simply add a parent div to the content with a class and use css instead of ng-style? – Yaser Feb 22 '17 at 21:01
  • The log to be applied is dynamic, and its to save the developer having to put ngAttributes on their content that they don't need to think about. – tic Feb 22 '17 at 21:21

0 Answers0