2013-06-02 128 views
2

如何覆蓋基於子域的模板URL?通過AngularJS子域動態路由

我的所有子域都指向同一個doc根目錄。

基地級域:example.com

$routeProvider.when('/', {templateUrl: 'views/example.com/home.html'}); 

子域:sub.example.com

$routeProvider.when('/', {templateUrl: 'views/sub.example.com/home.html'}); 

局部模板應無所謂靜態/動態內容。如果部分內部的控制器正在進行數據服務調用,則該攔截器不應干擾該數據。

+0

您的模板url看起來只是您的索引文件路徑的相對路徑。所以要更改域名(小心同源策略),您必須使這些路徑爲絕對路徑,可能使用常量來配置它們。 –

+0

@xmltechgeek對不起,但我想你可能跳過了子域指向同一個doc根的部分--- SOP與它無關。這裏的問題是,我需要一種檢測域的方法,而不是攔截「templateUrl」並將其更改爲不同的子域。 –

+0

不知道你會用默認的角度路由器做到這一點。你應該可以使用angular-ui團隊的ui-router(https://github.com/angular-ui/ui-router)中的templateProvider來做到這一點。請參閱https://github.com/angular-ui/ui-router/wiki#alternative-ways-to-set-the-template。 –

回答

2

的延續FO這個問題導致this question,但得到的答覆是同時適用於:

我決定去與本地stradegy有兩個原因:

  1. 沒有額外的XML請求開銷。
  2. 當資源不存在時,404消息不會監視控制檯日誌。

services.js

factory('Views', function($location,$route,$routeParams,objExistsFilter) { 

    var viewsService = {}; 
    var views = { 
    subdomain1:{ 
     'home.html':'/views/subdomain1/home.html' 
     }, 
    subdomain2:{ 

    }, 
    'home.html':'/views/home.html', 
    }; 

    viewsService.returnView = function() { 
    var y = $route.current.template; 
    var x = $location.host().split("."); 
    return (x.length>2)?(objExistsFilter(views[x[0]][y]))?views[x[0]][y]:views[y]:views[y]; 
    }; 

    viewsService.returnViews = function() { 
    return views; 
    }; 

    return viewsService; 
}). 

controllers.js

controller('AppController', ['$scope','Views', function($scope, Views) {  
    $scope.$on("$routeChangeSuccess",function($currentRoute, $previousRoute){ 
    $scope.page = Views.returnView(); 
    }); 
}]). 

filters.js

filter('objExists', function() { 
    return function (property) { 
    try { 
     return property; 
    } catch (err) { 
     return null 
    } 
    }; 
}); 
3

簡單又幹淨:我會在設置路由的函數中檢查window.location,根據子域設置一個變量,然後在設置路由時使用該變量。如:

var isSubDomain = window.location.host.indexOf("sub") == 0 
var urlPath = isSubDomain ? "sub.example.com" : "example.com"; 

... 

$routeProvider.when('/', {templateUrl: 'views/' + urlPath + '/home.html'}); 

TL; DR:使用JavaScript,沒有棱角

+1

考慮到已經有可用的主機名的路由提供者,這很髒。你可以訪問'$ location.host()'wihtin'.run()' –

+0

So Dan如果他使用$ location。主機()這將是好的,更容易閱讀比右上方? – HaveAGuess