Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat and insert directives

I have 3 different directives, <one>, <two>, <three>.

I want to loop through their ids and insert them in an ng-repeat

<ul>
    <li ng-repeat="panel in panels">
        <panel>
            <!-- panel.id would give me "one", "two" etc. -->
            <!-- First insert <one> then <two> etc -->
        </panel>
    </li>
</ul>

The resulting html I would like to achieve then would be:

<ul>
    <li>
        <panel>
            <one></one>
        </panel>
    </li>
    <li>
        <panel>
            <two></two>
        </panel>
    </li>
    <li>
        <panel>
            <three></three>
        </panel>
    </li>
</ul>

And since each has its template:

<ul>
    <li>
        <div class="panel">
            <div id="one">
            </div>
        </div>
    </li>
    <li>
        <div class="panel">
            <div id="two">
            </div>
        </div>
    </li>
    <li>
        <div class="panel">
            <div id="three">
            </div>
        </div>
    </li>
</ul>

I am not sure how to do this? Is this possible? do I have to ng-compile to have a directive inside a directive?

Should I use just one directive and use an ng-switch?

Am I missing a more straightforward approach?

I know this works:

make a <panel-content> directive.

I include this on the <panel> directive:

make an

<ng-switch="panel.id">
    <ng-switch-when="one">
    <ng-switch-when="twp">
    <ng-switch-when="three">
</ng-switch>`

But it seems cumbersome.

like image 787
Trufa Avatar asked Apr 13 '15 12:04

Trufa


1 Answers

The way that I normally do this is use one directive that picks the specific directive in the link function. That prevents all of the ng-switch bloat.

html

<panel type='one'></panel>
<panel type='two'></panel>

js

angular.module('app').directive('panel', ['$compile', '$injector', function ($compile, $injector) {
    return {
        restrict: 'E',
        scope: {
            type: '='
        },
        link: function ($scope, element, attrs, vm) {
            var template;
            switch($scope.type){
                case 'one':
                    template = '<one></one>';
                    break;
                case 'two':
                    template = '<two></two>';
                    break;
            }
            element.html(template);
            $compile(element.contents())($scope);
        }
    };
}]);

Here's a fiddle showing this in action: http://jsfiddle.net/7cufjqs3/1/

like image 83
TwitchBronBron Avatar answered Sep 23 '22 10:09

TwitchBronBron