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.
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.
<panel type='one'></panel>
<panel type='two'></panel>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With