Dynamic template Angular UI-Router

Issue

I’m trying to load a navbar according to the user.

To do this, I need to set a dynamic template, but I can’t see my $rootScope

$stateProvider
    /*Login*/
    .state('login', {
        url: '/',
        data: {pageTitle: 'Inicio de sesiĆ³n.'},
        resolve: {},
        views: {
            'navbar': {
                templateUrl: null,
                controller: null
            },
            'body': {
                templateUrl: "views/login.html",
                controller: 'LoginController'
            }
        }
    })
    .state('home', {
        url: '/home',
        data: {pageTitle: 'Home.'},
        views: {
            'navbar': {
                templateUrl: "views/navbar.html", //here dinamyc template
                controller: null
            },
            'body': {
                templateUrl: "views/inicio.html",
                controller: null
            }
        }
    })
    .state('perfil', {
        url: '/perfil',
        data: {pageTitle: 'Perfil de usuario.'},
        views: {
            'navbar': {
                templateUrl: function (sessionProvider) {
                    var sessionFactory = sessionProvider.path();
                    return sessionFactory;
                }, // this return a tring, but don't load anything
                controller: null
            },
            'body': {
                templateUrl: "views/usuario/perfil.html",
                controller: 'UsuarioController'
            }
        }
    });

i’ve tried use a service to load the data, but it didnt work, also tried to load it from the localStorageService, but don’t display anything.

is there a single way to load it ?

Solution

There are features for this, like templateUrl and templateProvider. See all details here:

Trying to Dynamically set a templateUrl in controller based on constant

E.g. this could be an example of templateProvider used isntead of the ‘templateUrl’ static path

templateProvider: function(CONFIG, $templateRequest) {
    console.log('in templateUrl ' + CONFIG.codeCampType);

    var templateName = 'index5templateB.html';

    if (CONFIG.codeCampType === "svcc") {
         templateName = 'index5templateA.html';
    } 

    return $templateRequest(templateName);
},

Answered By – Radim Köhler

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published