Angular.js directive dynamic templateURL

angularjs, angularjs-directive

Solution

You can use `ng-include` directive.

Try something like this:

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.getContentUrl = function() {
                return 'content/excerpts/hymn-' + attrs.ver + '.html';
           }
       },
       template: '<div ng-include="getContentUrl()"></div>'
   }
});

UPD. for watching `ver` attribute

emanuel.directive('hymn', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
           attrs.$observe("ver",function(v){
               scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
           });
       },
       template: '<div ng-include="contentUrl"></div>'
   }
});

Problem

I have a custom tag in a `routeProvider` template that that calls for a `directive` template. The `version` attribute will be populated by the scope which then calls for the right template. ``` <hymn ver="before-{{ week }}-{{ day }}"></hymn> ``` There are multiple versions of the hymn based on what week and day it is. I was anticipating to use the directive to populate the correct `.html` portion. The variable is not being read by the `templateUrl`. ``` emanuel.directive('hymn', function() { var contentUrl; return { restrict: 'E', link: function(scope, element, attrs) { // concatenating the directory to the ver attr to select the correct excerpt for the day contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html'; }, // passing in contentUrl variable templateUrl: contentUrl } }); ``` There are multiple files in excerpts directory that are labeled `before-1-monday.html`, `before-2-tuesday.html`, …

Original source

Related problems