I am new to Angularjs and I would like to add dynamic subdomain such as sub.domain.com
.
By changing sub, I would be able to ask the proper data from the server. However, the home page will still be the same.
sub1.domain.com
and sub2.domain.com
will have the same home.tpl.html
page except that the data returned will be specific to the domain.
It will be the same for other pages too.
Is there a way to do that?
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!