2

I try to parameterize the template of a page using a directive. I have an array of objects with a 'type' value. I want to use different templates when types are different.

Here is what I tried:

directive.js

angular.module('core')
  .directive('mySolutionDisplay', function () {
    return {
      restrict: 'E',
      scope: {
        solution: '='
      },
      templateUrl: function (elem, attr) {
        return 'path/to/template/solution-'+attr.type+'.template.html';
      }
    };
  });

view.html

<div class="row">
  <my-solution-display type="vm.solution[0].type" solution="vm.solution"></my-solution-display>
</div>

I get the following error : angular.js:11706 Error: [$compile:tpload] Failed to load template: path/to/template/solution-vm.solution[0].type.template.html

I tried replacing type="vm.solution[0].type" by type="{{vm.solution[0].type}}" but it just added the curly brackets to the error message.

JulienM
  • 134
  • 1
  • 6

1 Answers1

0

Attributes (attrs) has no access to scope variable. They get the dom value after they have been interpolated.

So, use

<my-solution-display type="{{vm.solution[0].type}}" solution="vm.solution"> </my-solution-display>

Note how type="vm.solution[0].type" was changed to type="{{vm.solution[0].type}}"

Chanthu
  • 1,794
  • 1
  • 15
  • 22
  • I already tried this but it just adds the curly brackets in the error description. `angular.js:11706 Error: [$compile:tpload] Failed to load template: path/to/template/solution-{{vm.solution[0].type}}.template.html` – JulienM Aug 08 '16 at 11:00
  • 1
    Yeah, ignore my answer. Looks like that's just not possible. See the bug: https://github.com/angular/angular.js/issues/13526. Have a look at: http://stackoverflow.com/questions/21835471/angular-js-directive-dynamic-templateurl for another way of solving this problem. – Chanthu Aug 08 '16 at 11:31