重复并插入指令

Tru*_*ufa 6 javascript angularjs angularjs-directive angularjs-ng-repeat

我有3级不同的指令,<one>,<two>,<three>.

我想循环它们的id并将它们插入到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>
Run Code Online (Sandbox Code Playgroud)

我想要实现的结果是:

<ul>
    <li>
        <panel>
            <one></one>
        </panel>
    </li>
    <li>
        <panel>
            <two></two>
        </panel>
    </li>
    <li>
        <panel>
            <three></three>
        </panel>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

因为每个都有它的模板:

<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>
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做?这可能吗?我必须在ng-compile指令中有一个指令吗?

我应该只使用一个指令并使用ng-switch

我错过了一种更简单的方法吗?

我知道这有效:

制定<panel-content>指令.

我在<panel>指令中包括这个:

做一个

<ng-switch="panel.id">
    <ng-switch-when="one">
    <ng-switch-when="twp">
    <ng-switch-when="three">
</ng-switch>`
Run Code Online (Sandbox Code Playgroud)

但这似乎很麻烦.

Twi*_*ron 2

我通常执行此操作的方法是使用一个指令来选择链接函数中的特定指令。这可以防止所有 ng-switch 的膨胀。

html

<panel type='one'></panel>
<panel type='two'></panel>
Run Code Online (Sandbox Code Playgroud)

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);
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

这是一个显示此操作的小提琴:http://jsfiddle.net/7cufjqs3/1/