Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic subdomain with angularjs

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?

like image 331
kennyT07 Avatar asked Oct 14 '14 00:10

kennyT07


2 Answers

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
}]);
like image 52
GregL Avatar answered Nov 24 '22 20:11

GregL


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.

like image 38
Rezvan Chagaev Avatar answered Nov 24 '22 20:11

Rezvan Chagaev