2

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.