Is it possible to change templateUrl on the fly by passing values in the directive’s scope?
I want to pass data to controller that will render the page based on the data that passed from the directive
something maybe that looks like that:
<div>
<boom data="{{myData}}" />
</div>
.directive('boom', function {
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { data: 'bind' },
templateUrl: "myTemplate({{boom}}})" // <- that of course won't work.
}
});
It is possible, but when your template to be loaded depends on some scope-data you can’t use the directive’s
templateUrlproperty anymore and you will be obliged to use lower-level API, namely$httpand$compile.Roughly what you need to do (only possible in the linking function) is to retrieve template’s content using
$http(don’t forget to involve$templateCache!) and then compile template’s content “manually”.It might sound like it is a lot of work but in practice it is rather straightforward. I would suggest having a look at the
ngIncludedirective sources where this pattern is used.Here is a skeleton of such a directive:
assuming that it would be used as
<boom data='name'></boom>. Working plunk here: http://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8?p=previewPlease note that I’ve changed attributes evaluation from
{{name}}to attributes parsing since probably a template should be determined only once, at the beginning.