dynamic subdomain with angularjs

别等时光非礼了梦想. 提交于 2019-12-01 17:48:17

The main thing you need to look at is the $location service, in particular the $location.host() method. That will return you the full domain, from there it is easy to get the subdomain and use that.

You could even do a really simple service that you could inject anywhere to get access to the subdomain easily.

Something like:

app.factory('subdomain', ['$location', function ($location) {
    var host = $location.host();
    if (host.indexOf('.') < 0) 
        return null;
    else
        return host.split('.')[0];
}]);

Then you can use this as a simple injectable value in your controllers, directives, etc.

app.controller('SomeCtrl', ['$scope', 'subdomain', function ($scope, subdomain) {
     // use subdomain same as any other variable
}]);

Subdomains are served by server, angular in turn serves hash/hashbang urls and knows nothing about subdomain.

U can have 3 subdomain, for example:

  • en.example.com (configured manually on server)|
  • de.example.com (configured manually on server)| -> example.com
  • it.example.com (configured manually on server)|

Each of them refers to the main example.com, but you wanna achieve something by using subdomains, for example i18n (with angular).

Thus, when someone connects to en.example.com (in fact, the request goes to example.com where you angular app is hosted) you can extract subdomain in angular(en in this case, see example in the post above) and translate you angular view.

Why no split by dots and count the elements of 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;

hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!