Repeat and insert directives

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

I want to scroll their ids and paste them into 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 that I would like to achieve will be as follows:

 <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 own 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'm not sure how to do this? Is it possible? do i need ng-compile have a directive inside a directive?

Should I use only one directive and use ng-switch ?

Am I missing a simpler approach?

I know this works:

create the <panel-content> directive.

I include this in the <panel> directive:

to do

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

But that seems cumbersome.

+6
source share
3 answers

As usual I do this, use one directive that selects a specific directive in the link function. This prevents the ng switch surge.

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 is a fiddle showing this in action: http://jsfiddle.net/7cufjqs3/1/

+2
source

If you are ready to live with an extra div between your directive and the panel element, I created a dynamic directive that knows nothing about the name of the element and creates it dynamically:

Using

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

Directive

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

Fiddle

0
source

I think this is the best approach because it is most readable in your 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

0
source

Source: https://habr.com/ru/post/985060/


All Articles