Access node name inside AngularJS configuration

Since you cannot use access services inside .config , how can I access properties such as $host , usually found in $locationService ?

I am trying to load partial data based on the current subdomain. All subdomains point to the base root of the doc domain.

When viewing:

 example.com 

templateUrl will be:

 views/home.html 

When viewing:

 spicy.example.com 

templateUrl will be:

 views/spicy/home.html 
+4
source share
2 answers

In the app.run method, you can use the $ routeChangeStart event to intercept only until the route is completed. In your .config, specify 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 to .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 in the view / <host> /home.html

Plunger example: http://embed.plnkr.co/82qV7uCZOBgZxjahhlU3/ Note that I use _ instead of / to simulate the directory in which the file is located, based on the host name. Plunker does not like / in the file name (refused to save the file, although I was able to run it)

+7
source

You can access $$ host in config. You simply cannot use $ location. Use $ urlRouterProvider instead. However, $ urlRouterProvider for some reason makes the $ location empty, so you can also use a clean javascript window to get the url node if you change the env configuration based on different URL nodes.

eg.

 function config($urlRouterProvider) { if ($urlRouterProvider._router.locationService.$location) console.log(console.log($urlRouterProvider._router.locationService.$location.$$host)) else console.log(window.location.host) } 
0
source

Source: https://habr.com/ru/post/1483992/


All Articles