Angular and UI-Router, how to set a dynamic templateUrl

As discussed in this Q & A: Angular UI Router: decide child state template on the basis of parent resolved object, we can do that like this

This could be a service playing role of “from Server/DB loading template name”:

.factory('GetName', ['$http', '$timeout',
    function($http, $timeout) {
      return {
        get : function(id) {
          // let's pretend server async delay
          return $timeout(function(){
            // super simplified switch... but ...
            var name = id == 1
                  ? "views.view2.html"
                  : "views.view2.second.html"
                  ;
            return {templateName : name}; 
          }, 500);
        },
      };
    }
]);

Then the templateProvider defintion would look like this:

  views: {
    "page": {
      templateProvider: function($http, $stateParams, GetName) {

        // async service to get template name from DB
        return GetName
            .get($stateParams.someSwitch)
            // now we have a name
            .then(function(obj){
               return $http
                  // let's ask for a template
                  .get(obj.templateName)
                  .then(function(tpl){
                      // haleluja... return template
                      return tpl.data;
               });      
            })

      }, 

The code should be self explanatory. Check this answer and its plunker for more details

Leave a Comment