Lazy load template and controller in angular UI-Router

后端 未结 2 562
予麋鹿
予麋鹿 2020-12-09 19:02

I am attempting to lazy load a controller and template in my UI-Router router.js file, but am having difficulty with the template.

The controller loads properly, but

2条回答
  •  无人及你
    2020-12-09 19:27

    In case you'd like to lazily load the controller, I would suggest follow these detailed answers:

    • requirejs with angular - not resolving controller dependency with nested route
    • angular-ui-router with requirejs, lazy loading of controller

    In case we need to load dynamically the HTML template, it is much more easier. There is an example from this Q & A

    • Trying to Dynamically set a templateUrl in controller based on constant

    (the working plunker)

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

    You can check these as well:

    • Angular UI Router: decide child state template on the basis of parent resolved object
    • Angular and UI-Router, how to set a dynamic templateUrl

提交回复
热议问题