Search code examples
angularjsangularjs-directiveangularjs-ng-repeat

Angularjs templateUrl fails to bind attributes inside ng-repeat


I'm using directive to display html snippets.

And templateUrl inside the directive, to be able to include snippets as html file.

The directive does not work, if I try to call inside a builtin ng-repeat directive ({{snip}} is passed as is, without substitute):

div ng-repeat="snip in ['snippet1.html','snippet2.html']">
  <my-template snippet="{{snip}}"></my-template>
</div>

For reference, here is the directive:

app.directive("myTemplate", function() {
return {
    restrict: 'EA',
    replace: true,
    scope: { snippet: '@'},
    templateUrl: function(elem, attrs) {
      console.log('We try to load the following snippet:' + attrs.snippet);
      return attrs.snippet;
    }
  };
});

And also a plunker demo.

Any pointer is much appreciated. (the directive is more complicated in my code, I tried to get a minimal example, where the issue is reproducible.)


Solution

  • attrs param for templateUrl is not interpolated during directive execution. You may use the following way to achieve this

    app.directive("myTemplate", function() {
      return {
        restrict: 'EA',
        replace: false,
        scope: { snippet: '@'},
        template: '<div ng-include="snippet"></div>'
      };
    }); 
    

    Demo: http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview