Trying to Dynamically set a templateUrl in controller based on constant

I created a plunker here
You are almost there, just the syntax is 'templateProvider':

.state('home', {
    url: '/home',
    //templateUrl: 'index5templateA.html',   (THIS WORKS)
    // templateUrl: function(CONFIG) {
    templateProvider: function(CONFIG) {
    ...

Snippet from doc:

Templates

TemplateUrl
templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is NOT injected.

TemplateProvider
Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:

So in our case, that would be the implementation:

 $stateProvider
    .state('home', {
        url: '/home',
        //templateUrl: 'index5templateA.html',   (THIS WORKS)
        templateProvider: function(CONFIG, $http, $templateCache) {
            console.log('in templateUrl ' + CONFIG.codeCampType);
            
            var templateName="index5templateB.html";
            
            if (CONFIG.codeCampType === "svcc") {
                 templateName="index5templateA.html";
            } 
            var tpl = $templateCache.get(templateName);
            
            if(tpl){
              return tpl;
            }
            
            return $http
               .get(templateName)
               .then(function(response){
                  tpl = response.data
                  $templateCache.put(templateName, tpl);
                  return tpl;
              });
        },
        controller: function ($state) {
        }
    });

Check the examle here

Also check:

Leave a Comment