Reputation: 1829
Let's say I have a few directives: "drama", "comedy" and for some reason they have a lot of different properties, so it does not necessarily make sense to have a "movie" directive. Is there a way to dynamically evaluate a directive based on a scope variable? Something like this:
<{{movieType}} movie="{{movie}}"></{{movieType}}>
Where it would evaluate to something like this:
<comedy movie={{movie}}></comedy>
I'm new to Angular, so pardon for crazy ideas.
UPDATE: Actually just found a neat article regarding the exact same problem/solution: http://onehungrymind.com/angularjs-dynamic-templates/
Basically author has a single directive, but swaps out the templates based on the request:
var getTemplate = function(contentType) {
var template = '';
switch(contentType) {
case 'image':
template = imageTemplate;
break;
case 'video':
template = videoTemplate;
break;
case 'notes':
template = noteTemplate;
break;
}
return template;
}
return {template: getTemplate(type)};
Upvotes: 0
Views: 147
Reputation: 52847
You could use a template function inside of a directive:
app.directive('movie', function(){
return {
restrict:'A',
template: function(element, attr){
... define templates, i.e. <comedy />
var contentType = attr.movie;
switch(contentType) {
case 'comedy':
template = comedyTemplate;
break;
case 'drama':
template = dramaTemplate;
break;
case 'suspense':
template = suspenseTemplate;
break;
}
return template;
}
}
})
With this solution, no manual compilation is necessary.
Upvotes: 1