Angular UI-router and using dynamic templates

前端 未结 1 1091
不知归路
不知归路 2021-01-07 05:25

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

相关标签:
1条回答
  • 2021-01-07 05:49

    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

    0 讨论(0)
提交回复
热议问题