AngularJS directive dynamic templates

Solution 1:

You can set the template property of your directive definition object to a function that will return your dynamic template:

restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
    return getTemplate(tAttrs.content);
}

Notice that you don't have access to scope at this point, but you can access the attributes through tAttrs.

Now your template is being determined before the compile phase, and you don't need to manually compile it.

Solution 2:

You can also do it very straightforward like this:

appDirectives.directive('contextualMenu', function($state) {
    return {
      restrict: 'E',
      replace: true,
      templateUrl: function(){
        var tpl = $state.current.name;
        return '/app/templates/contextual-menu/'+tpl+'.html';
      }
    };
});