I am trying to create a directive that will display a list of objects from my controller. Inside this directive, I want to be able to use one of several possible sub-directives, but the specific one to be used may vary. If I set the sub-directive name in the controller's scope, how can I dynamically incorporate it within the template of the main directive?
Here's a plnkr with the code shown 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!'
};
});
Currently, I have set the $scope.directiveName
to dinosaurs
, which is the sub-directive I want to include within the main directive called prog
.
In the template of prog
, I am trying to dynamically insert the name of the sub-directive. However, the output shows:
- <dinosaurs>Rush
- <dinosaurs>King Crimson
- <dinosaurs>Porcupine Tree
- <dinosaurs>Marillion
I have also attempted using a class name on a span: , but Angular does not recognize it as a directive in this case.
I am unsure if using an isolate scope is necessary here, and I am still learning about transclusion. My goal with the dinosaurs
directive is to append " - DINOSAURS!" to the content of each list item.
What is the most effective way to pass the name of one directive to another in Angular?