Angular — Directives: using a dynamic template

Directives are a very powerful concept in Angular. Let’s say we want to create a directive to display user profiles. The final directive should be used like this

Follow me on Twitter for latest updates @gerardsans.

Internally we want the directive to change the template being used based on the user type. In order to setup a template for your directive you can use template or templateUrl options.

This would be the initial version

Profile directive (using template)

This works fine but still does not take into account the type. We can move the template to a file first and use templateUrl.

Profile directive (using templateUrl)

In order to implement the dynamic template we can’t use any of the two so we have to resort to another approach using ng-include. We can’t use templateUrl as it has no access to $scope.user.type.

The solution is to make use of ng-include and resolve the src attribute on the controller.

Dynamic template using ng-include

Demo code: link

Thanks for reading! Have any questions? Ping me on Twitter @gerardsans.