重复并插入指令



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

我想遍历他们的 ID 并将它们插入 ng 重复

<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>

然后我想实现的结果 html 将是:

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

由于每个都有其模板:

<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>

我不确定该怎么做?这可能吗?我必须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>`

但这似乎很麻烦。

我通常这样做的方法是使用一个指令来选择链接函数中的特定指令。这可以防止所有的ng开关膨胀。

.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);
        }
    };
}]);

这里有一个小提琴在实际操作中展示这一点:http://jsfiddle.net/7cufjqs3/1/

如果你愿意在你的指令和panel元素之间有一个额外的div,我创建了一个动态指令,它对元素的名称一无所知,并动态创建它:

用法

<li ng-repeat="panel in panels">       
    <panel>
       <dynamic-directive element="panel.id"></dynamic-directive>
    </panel>
</li>

指令

myApp.directive('dynamicDirective', function($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "<div></div>",
        scope: {
            element: "="
        },
        link: function(scope, element, attrs) {
            var elm = '<' + scope.element + '></' + scope.element + '>';
            element.html(elm);
            $compile(element.contents())(scope);
        }
    }
});

小提琴

我认为开关是最好的方法,因为它在您的 html 中最具可读

<ul>
    <li ng-repeat="panel in panels">
        <panel ng-switch on="panel.id">
          <div ng-switch-when="one"><one>1</one></div>
          <div ng-switch-when="two"><two>2</two></div>
          <div ng-switch-when="three"><three>3</three></div>
        </panel>
    </li>
</ul>

http://plnkr.co/edit/ygy6coKCyQNGBoKmSES0?p=preview

最新更新