It's me ... Alex
It's me ... Alex

Reputation: 289

Angular wrap transcluded elements separately?

I am fairly new with Angular. And although I've made a lot of progress there are still a couple of things I don't know.

Currently I am running into a transclusion 'problem'.

Basically what we want is to wrap every transcluded element/directive seperately with html that's controlled by the parent directive.

Example:

<my:directive>
    <my:sub-directive>Child 1</my:sub-directive>
    <my:sub-directive>Child 2</my:sub-directive>
    <my:sub-directive>Child 3</my:sub-directive>
</my:directive>

Desired result (I've left the directive elements to make the example a bit more clear):

<my:directive>
    <ul>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 1</my:sub-directive>
                </div>
            </div>
        </li>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 2</my:sub-directive>
                </div>
            </div>
        </li>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 3</my:sub-directive>
                </div>
            </div>
        </li>
    </ul>
</my:directive>

Does anyone have a clue how to handle this? I know in my example I could introduce a panel directive, but note this is just an example of the same problem.

Upvotes: 3

Views: 722

Answers (1)

Joao Leal
Joao Leal

Reputation: 5542

You can pass a fifth parameter to your directive's link function transclude and then do your manipulation in there, here's a quick example:

angular.directive('myDirective', function ($compile) {
    return {
        restrict:'EA',
        transclude:true,
        link: function (scope, elm, attrs,ctrl,transclude) {
            transclude(scope,function(clone) {
                //clone is an array of whatever is inside your main directive
                clone.filter('mySubDirective').each(function(index, value){
                    //create your html and you might have to $compile it before:
                    elm.append(myHtml);                    
                });
            });
        }
    };

})

Upvotes: 1

Related Questions