4

因为您无法访问内部服务,.config我将如何访问$host通常在中找到的属性$locationService

我正在尝试根据当前子域加载部分内容。所有子域都指向基本主机文档根。

查看时:

example.com

templateUrl 将是:

views/home.html

查看时:

spicy.example.com

templateUrl 将是:

views/spicy/home.html
4

2 回答 2

7

在 app.run 方法中,您可以使用 $routeChangeStart 事件在路由执行之前进行拦截。在您的 .config 中,将 templateURL 指定为模板本身的文件(例如 home.html,不带 /views)

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

然后您可以在.run中添加以下代码:

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

它将访问views/<host>/home.html下的home.html

Plunker 示例:http ://embed.plnkr.co/82qV7uCZOBgZxjahhlU3/ 请注意,我使用 _ 而不是 / 来根据主机名模拟文件所在的目录。Plunker 不喜欢文件名中的 / (尽管我能够运行它,但拒绝保存文件)

于 2013-06-02T03:36:00.210 回答
0

您可以在配置中访问 $$host。您只是不能使用 $location。而是使用 $urlRouterProvider。但是,$urlRouterProvider 出于某种原因将 $location 填充为空,因此如果您要根据不同的 url 主机更改配置环境,也可以使用纯 JavaScript 窗口来获取 url 主机。

例如

function config($urlRouterProvider) {
  if ($urlRouterProvider._router.locationService.$location)
    console.log(console.log($urlRouterProvider._router.locationService.$location.$$host))
  else
    console.log(window.location.host)
}
于 2017-07-18T18:36:02.643 回答