2013-06-02 130 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