2013-06-02 37 views
4

因爲你無法訪問.config內部的服務,我將如何訪問通常在$locationService中找到的$host屬性?在配置中訪問主機名AngularJS

我想加載基於當前子域的partials。 所有子域指向基本主機doc根目錄。

當觀看:

example.com 

templateUrl將是:

views/home.html 

當觀看:

spicy.example.com 

templateUrl將是:

views/spicy/home.html 

回答

7

在app.run方法中,您可以在執行路由之前使用$ routeChangeStart事件進行攔截。在你的.config,指定templateURL作爲模板本身的文件(例如,home.html的,不帶/視圖)

app.config(function ($routeProvider) { 
    $routeProvider 
     .when('/', { 
     templateUrl: 'home.html', 
     controller: 'HomeCtrl' 
     }); 
    ... 
}); 

,然後你可以在.RUN添加以下代碼:

app.run(function ($rootScope,$location){ 
    $rootScope.$on('$routeChangeStart',function(event,next,current){ 
     next.templateUrl = "views/"+$location.host()+"/"+next.templateUrl; 
    }); 
}); 

,它會根據意見訪問的Home.html/<主機> /home.html

Plunker例如:http://embed.plnkr.co/82qV7uCZOBgZxjahhlU3/ 請注意我用_代替/模擬目錄文件所在基於日e主機名。 Plunker不喜歡/在文件名中(拒絕保存文件,儘管我可以運行它)

+0

+1這看起來像我正在尋找的!但是,獲取錯誤:templateUrl未定義?另外,當我尾隨我的console.log()時,似乎我的摘要停留在循環中。你可以提供一個plunker /小提琴嗎? –

+0

我錯過了templateUrl之前的'next',因爲next有所有的屬性。我已經修復了上面的代碼。你只需要訪問下一個對象,並根據需要操作 – maethorr

+0

Mabye它將有助於做一個plunker /小提琴?我被困在一個循環中,我繼續重新加載所有的應用程序依賴關係。 –

0

您可以在config中訪問$$ host。你不能使用$位置。而是使用$ urlRouterProvider。但是,$ urlRouterProvider將$ location填充爲空,因此,如果您要根據不同的url主機更改配置env,則還可以使用純javascript窗口來獲取url主機。

E.g.

function config($urlRouterProvider) { 
    if ($urlRouterProvider._router.locationService.$location) 
    console.log(console.log($urlRouterProvider._router.locationService.$location.$$host)) 
    else 
    console.log(window.location.host) 
} 
相關問題