Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access host name inside config AngularJS

Because you cant access services inside .config how would I get access to properties like $host normally found in $locationService ?

I am trying to load partials based on current subdomain. All subdomains point to base host doc root.

When viewing:

example.com

templateUrl would be:

views/home.html

When viewing:

spicy.example.com

templateUrl would be:

views/spicy/home.html
like image 828
Dan Kanze Avatar asked Mar 24 '23 17:03

Dan Kanze


1 Answers

In the app.run method, you can use $routeChangeStart event to intercept just before route is executed. In your .config, specify the templateURL as the file of the template itself (e.g home.html, without /views)

app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        controller: 'HomeCtrl'
      });
    ...
});

and then you can add the following code in the .run:

app.run(function ($rootScope,$location){
    $rootScope.$on('$routeChangeStart',function(event,next,current){
        next.templateUrl = "views/"+$location.host()+"/"+next.templateUrl;
    });
});

and it will access home.html under views/<host>/home.html

Plunker example: http://embed.plnkr.co/82qV7uCZOBgZxjahhlU3/ Please note I use _ instead of / to simulate directory where the file resides based on the hostname. Plunker doesn't like / in the filename (refused to save the file although I was able to run it)

like image 124
maethorr Avatar answered Apr 02 '23 19:04

maethorr