I want to choose which directive to use based on a variable. Specifically, I have items of several different types in a list, so I would like to use the item type to choose the directive that can display it.
ng-switch seems intended for this purpose. However, it adds all of the switch choices into the DOM, then hides all but one. That approach seems inefficient if there are many item types or a long list to display. Also, using a switch puts the logic in the HTML. Preferred would be a 'strategy pattern' that would just choose the right directive, perhaps like
<display-{{item.type}} data="item.data" />
where the directives are 'displayType1', 'displayType2', and so on. However, this syntax seems not to work, perhaps because of the difference between the compile and linking phases. Here is an example that switches html templates inside a directive. But is there a way to switch directives, retaining their modularity?
Adding the solution based on @CodeGuy2001 advice.
The approach to take here is to create a angular template for each of the directive variation with a different template name.
Then use the ng-include
to select the template that needs to be used. Since ng-include
supports data binding to src
property. You can switch template and hence directives dynamically.
See the fiddle in action http://jsfiddle.net/xpKwb/2/
I'm not aware of a way to add a dynamic directive name like that. A couple of alternative ideas:
1) Just use one single directive with item.type as a paramter, and have the directive act differently depending on it's value.
2) Instead of ng-switch, use ng-if which actually removes the element from the DOM rather than hiding it (like ng-hide or ng-switch)
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