gpt4 book ai didi

javascript - 重复和插入指令

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:09 25 4
gpt4 key购买 nike

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

我想实现的结果 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-switch 膨胀。

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

这里有一个 fiddle 展示了这个 Action :http://jsfiddle.net/7cufjqs3/1/

关于javascript - 重复和插入指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29604939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com