如何根据客户设置更改角度UI路由器的templateURL

时间:2015-09-05 09:53:28

标签: angularjs angular-ui-router

我的角度应用程序上有多个客户端,我想在角度内创建不同的主题(只有视觉部分会改变,控制器保持不变。

我有一个"安全"管理身份验证的模块,currentLoggedIn用户等。

var security = angular.module('security', ['ui.router'])
    // .factory('authService',  authService);
.service('authService', ['$http', '$q', '$window', 'CONSTANTS', '$location', 'currentUser', '$state', '$rootScope', authService])
.factory('authCheck', ['$rootScope', '$state', 'authService', securityAuthorization])

和authService基本上都有这些方法/值

service.login = _login;
    service.logout = _logout;
    service.reset = _reset;
    service.isAuthenticated = _isAuthenticated;
    service.requestCurrentUser = _requestCurrentUser;
    service.returnCurrentUser = _returnCurrentUser;
    service.hasRoleAccess = _hasRoleAccess;

如何在templateURL函数内访问currentUser以根据currentUser的数据修改URL? 在templateURL函数中访问时,AuthService和AuthCheck为空。

$stateProvider
        .state('home', {
            url: '/home',
            templateUrl: function(authService, authCheck) {
                console.log (authService, authCheck);
                return 'components/home/home.html'
            },
            data: {
                roles: ['Admin']
            },
            resolve: {
                "authorize": ['authCheck', function(authCheck) {
                    return authCheck.authorize();
                }],
                "loadedData": ['metricsFactory', 'campaignFactory', '$q', '$rootScope', 'selectedDates', loadHomeController]
            },
            controller: 'HomeController',
            controllerAs: 'home'
        });

2 个答案:

答案 0 :(得分:1)

如果我们想在返回模板之前做一些“魔术”......我们应该使用templateProvider。检查此Q&答:

Trying to Dynamically set a templateUrl in controller based on constant

因为template:...可以是字符串,也可以是这样的函数(查看doc:)

<强> $ stateProvider

  

模板

     

html模板作为字符串或返回html模板的函数   作为uiView指令应该使用的字符串。这个   property优先于templateUrl。

     

如果template是一个函数,将使用以下函数调用它   参数:

     

{array。} - 从当前提取的状态参数   $ location.path()通过应用当前状态

template: function(params) {
    return "<h1>generated template</h1>"; }

使用templateProvider,我们可以获得任何注入的内容,例如角度$ templateRequest的巨大改进。检查这个答案和它的plunker

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

    var templateName = 'index5templateB.html';

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

    return $templateRequest(templateName);
},

答案 1 :(得分:0)

来自the documentation

  

templateUrl(可选)

     

返回应由uiView使用的html模板路径的路径或函数。

     

如果templateUrl是一个函数,它将使用以下参数调用:

     

{array。&lt; object&gt;} - 通过应用当前状态从当前$ location.path()中提取的状态参数

因此,显然,您无法向templateUrl函数注入服务。

但是之后,文档也说:

  

templateProvider(可选)

     

功能

     

返回HTML内容字符串的提供程序函数。

templateProvider:
    function(MyTemplateService, params) {
      return MyTemplateService.getTemplate(params.pageId);
    }

允许做你想做的事。

相关问题