Reputation: 742
I have a directive that looks at configuration to figure out what template to use. It used to work great; I had a Config service that just returned an object with config values, and then I did something like this:
if (Config.Values.ReleaseVersion < 1.0) {
template = 'partials/pagebeta.html';
}
else {
template = 'partials/page.html';
}
templateUrl: template
Recently a problem was introduced. My Config service has to get values from a json file. Now because getting config is async, I am now passing back a promise from the Config service. This is creating problems for me in my directive - I can't do this:
var template;
Config.then(function(config) {
if (config.Values.ReleaseVersion < 1.0) {
template = 'partials/pagebeta.html';
}
else {
template = 'partials/page.html';
}
});
templateUrl: template
Any suggestions are appreciated!
Upvotes: 2
Views: 1181
Reputation: 117370
If your templateUrl depends on the value computed asynchronously you can't use the directive's templateUrl
property anymore and you will be obliged to use lower-level API, namely $http
and $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 ngInclude
directive sources where this pattern is used.
Upvotes: 2