Angular UI-router and using dynamic templates

ぃ、小莉子 提交于 2019-12-12 07:22:20

问题


I'm trying to load a template file using a rootscope value as for it's name. I have a init controller which sets the $rootScope.template to "whatever.html", then I have my route like this:

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

But this doesn't work. It actually freezes the whole chrome so that I have to kill the process in order to stop it... I've also tried this with templateUrl but with no results.

So how could I use my dynamic template file with UI-router?


回答1:


Similiar to your other question (in order I found them): Angular and UI-Router, how to set a dynamic templateUrl, I also created a working plunker to show how to. How it would work?

So, if this would be state call:

<a href="#/parent/child/1">#/parent/child/1</a>
<a href="#/parent/child/2">#/parent/child/2</a>

And these would be states:

  $stateProvider
    .state('parent', {
      url: '/parent',
      //abstract: true,
      templateUrl: 'views.parentview.html',
      controller: function($scope) {},
    });

  $stateProvider
    .state('parent.child', {
      url: '/child/:someSwitch',
      views: {
         // see more below

Then we can use this templateProvider definiton:

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;
           });      
        })

}, 

What we can see is chaining of async results:

// first return of promise
return asyncstuff
  .then(function(x){
    // second return of a promise once done first
    return asyncstuff
      .then(function(y){  
       // again  
        return asyncstuff
          .then(function(z){
            return ... it
          }
      }

  }

And that's what the magical templateProvider can do for us... wait until all promises are resolved and continue execution with known template name and even its content. Check the example here. More about template provider: Angular UI Router: decide child state template on the basis of parent resolved object



来源:https://stackoverflow.com/questions/26864152/angular-ui-router-and-using-dynamic-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!