Search code examples
angularjssubdomain

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?


Solution

  • 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
    }]);