我是Angularjs的新手,我想添加动态子域名,例如sub.domain.com
。
通过更改sub,我可以从服务器请求正确的数据。但是,主页仍然是相同的。
sub1.domain.com
和sub2.domain.com
将具有相同的home.tpl.html
页面,但返回的数据将特定于域。
其他页面也是如此。
有办法吗?
答案 0 :(得分:14)
您需要关注的主要问题是$location
service,尤其是$location.host()
method。这将返回完整的域名,从那里很容易获得子域名并使用它。
你甚至可以做一个非常简单的服务,你可以在任何地方注入,以便轻松访问子域。
类似的东西:
app.factory('subdomain', ['$location', function ($location) {
var host = $location.host();
if (host.indexOf('.') < 0)
return null;
else
return host.split('.')[0];
}]);
然后,您可以在控制器,指令等中将其用作简单的可注射值。
app.controller('SomeCtrl', ['$scope', 'subdomain', function ($scope, subdomain) {
// use subdomain same as any other variable
}]);
答案 1 :(得分:2)
子域名由服务器提供,角度反过来提供哈希/ hashbang网址,并且对子域名一无所知。
U可以有3个子域名,例如:
每个都引用主 example.com ,但你想通过使用子域来实现某些功能,例如i18n(带角度)。
因此,当有人连接到en.example.com时(实际上,请求转到example.com托管角色应用的example.com),您可以在角度中提取子域(在这种情况下, en ,请参阅上面帖子中的示例)并翻译角度视图。
答案 2 :(得分:2)
为什么不按点分割并计算host()的元素?
var host = $location.host();
var parts = host.split('.');
var subdomain = null;
// more than domain.cn, will always return the first
if (parts.length > 2)
subdomain = parts[0];
return subdomain;
希望它有所帮助!