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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With