I would like display a list of objects from my controller using a directive. Inside that directive I'd like to be able to use one of several possible directives, but I won't always know which one. If I set that directive name in the controller's scope, how can I use it within the template of the main directive?
Here's a plnkr with what's below.
HTML:
<div ng-app="music" ng-controller="rock">
<h1>Favorite Bands</h1>
<prog></prog>
</div>
JS:
angular.module('music', []);
angular.module('music').controller('rock', ['$scope', function($scope){
$scope.directiveName = 'dinosaurs';
$scope.bands = [
{ name:'Rush'}, { name:'King Crimson' }, { name: 'Porcupine Tree'}, { name: 'Marillion'}];
}]);
angular.module('music').directive('prog', function(){
return {
restrict: 'E',
replace: true,
template: '<ul><li ng-repeat="band in bands"><{{directiveName}}>{{band.name}}</{{directiveName}}></li></ul>'
};
});
angular.module('music').directive('dinosaurs', function(){
return {
restrict: 'E',
transclude: true,
template: '<ng-transclude></ngtransclude> - DINOSAUR!'
};
});
In this case, I'm setting the $scope.directiveName to dinosaurs, which is the name of the directive I want to use inside the main one, called prog.
In prog's template, I'm trying to use interpolation to insert the name of the directive into the brackets. That, however, outputs this:
- <dinosaurs>Rush
- <dinosaurs>King Crimson
- <dinosaurs>Porcupine Tree
- <dinosaurs>Marillion
I've also tried using class name on a span: , and that inserts "dinosaurs" into the span as a class but Angular doesn't then process it as a directive.
I'm not sure if I need an isolate scope here, but from what I've read I don't think that's relevant. I'm also new to transclusion, but I think that the dinosaurs directive should take the content of each list item and add " - DINOSAURS!" to the end of it.
What's the best practice way to go about passing in the name of one directive to another?