Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - load dynamic template HTML within directive

Tags:

angularjs

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.

like image 708
jwest Avatar asked Jan 30 '13 15:01

jwest


2 Answers

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!

like image 64
jwest Avatar answered Sep 23 '22 05:09

jwest


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.

like image 23
kinablej Avatar answered Sep 19 '22 05:09

kinablej