7

I have a directive which loads content from an external HTML file. Passed into this directive is some scope data which is used in the rendering of that HTML fragment. e.g.

<div class="{{cls}}" data-obj="{{obj}}" data-id="{{id}}">

<!-- remainder of content here -->

</div>

What I would like to do within this directive is to load a further HTML partial within this based on the original scope data passed into the directive. I can't seem to get this to work, but it should be something along the lines of the following:

<div class="{{cls}}" data-obj="{{obj}}" data-id="{{id}}">

<!-- remainder of content here -->

<div ng-include="partials/{{obj}}.html></div>

</div>

Using this, the file doesn't get included, but I don't get any errors either. Can anybody assist me here?

NB: I read this, which is a similar issue, but hasn't helped me.

UPDATE - I noticed in Chrome dev tools that the URL is being resolved as expected, but the file contents are not getting included. I thought from the docs that ng-include loaded and compiled the requested fragment, so I was expecting this to work.

Community
  • 1
  • 1
jwest
  • 735
  • 3
  • 11
  • 20

2 Answers2

17

Found a solution in the end, by declaring the following in the directive:

<div ng-include src="view.getView()"></div>

and the following in the directive controller:

$scope.view = {
    getView: function() {
        return "partials/" + $scope.obj + ".html";
    }
};

Works perfectly now!

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
jwest
  • 735
  • 3
  • 11
  • 20
  • 2
    You can simplify this a little, the issue is that it expects a string, not objects: `
    `. Notice that I put single quotes around any normal text, this is what you need to force it from object literals to a string.
    – Shane Gadsby Feb 17 '13 at 15:58
1

In comment on the comment of Shane Gadsby: it is not <div ng-include src="'partials/'+{{obj}}+'.html'"></div> but <div ng-include src="'partials/'+obj+'.html'"></div>. Your comment explains why 'this is what you need to force it from object literals to a string', so everything not in single quotes is handled by the compiler as a scope object.

UtopiaLtd
  • 2,520
  • 1
  • 30
  • 46
kinablej
  • 31
  • 4