Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How could I use a name fetched from my database as a templateUrl filename?

I've tried this:

$stateProvider.state('/', {
  url: '/',
  views: {
    page: {
      controller: 'HomeCtrl',
      templateProvider: function($templateFactory, $rootScope) {
        console.log("$rootScope.template")
        return $templateFactory.fromUrl('/templates/' + $rootScope.template);
      }
    }
  }
});

Which doesn't seem to work work if my $rootScope.template comes from a database query. Don't know why, but it doesn't work.

If in my controller I do $rootScope.template = "whatever.html" everything works ok, but if I query the template from database nothing happens at all. console.log("$rootScope.template") in templateProvider gives me nothing (the query itself works just fine).

Does the query simply take too long and it's therefore not ready for the router or what's happening here?

That am I doing wrong and how can I fix it?

like image 448
QlliOlli Avatar asked Nov 11 '14 15:11

QlliOlli


1 Answers

I created an example, which does use some json to be load as data from the server, check it here. This what the $http will recieve (in our simplifed examle)

// dataFromServer.json
{
  "1": "views.view2.html",
  "2": "views.view2.second.html"
}

So this will come via $http and we will use it to return the name

.factory('GetName', ['$http', '$timeout',
    function($http, $timeout) {
      return {
        get : function(id) {
          // let's get data via $http
          // here it is the list, but 
          // should be some GetById method
          return $http
            .get("dataFromServer.json")
            .then(function(response){

              // simplified converter
              // taking the $http result and 
              // by id gets the name
              var converter = response.data;
              var name = converter[id];

              return {templateName : name}; 
          });
        },
      };
}

As we can see, this time, we really go for server data, using $http the trick again is to return that promise

return $http // see the return
  .get....

and later, we return again... inside of the then

....
.then(function(response){
   ...
   return {templateName : name}; 
});

That Example is here

like image 79
Radim Köhler Avatar answered Nov 17 '22 10:11

Radim Köhler