Angular $ location.path()没有获得基本标记路径

时间:2015-08-11 13:47:46

标签: angularjs

我正在尝试获取应用程序的基本URL,以便我的服务可以动态地将http请求发送到后端。

app.js

angular.module('myApp', [])
    .controller('myCtrl', function($scope,$http,$location){
       var baseUrl = $location.protocol() +"://"+ $location.host()+":"+$location.port()+$location.path();
       console.log($location.path());
       $http.get(baseUrl+"person").success(data){
         $scope.data = data; 
      };
    });

我在index.html中设置了基本标记,例如<base href="/helloworld/">

当我尝试console.log("path: "+$location.path())时,它只显示path: /。所以它没有得到/helloworld值。 所以我想知道为什么会这样。无论如何,我们可以使用$location.absUrl()检索基本标记值。谢谢高级!

1 个答案:

答案 0 :(得分:2)

<base href="/helloworld/">$location.path()没有任何关系。 $location.path()获取当前路径,您在地址栏中看到的内容,解析它并将值返回给您。

<base>(来自w3schools.com

标记指定文档中所有相对URL的基本URL /目标。

例如:

<head>
   <base href="http://www.w3schools.com/images/" target="_blank">
</head>

<body>
   <img src="stickman.gif" width="24" height="39" alt="Stickman">
   <a href="http://www.w3schools.com">W3Schools</a>
</body>

在上面的示例中,浏览器会在stickman.gif找到http://www.w3schools.com/images/stickman.gif

$location.path() Source on GitHub

此代码仅查看当前网址,不考虑基本元素。

  path: locationGetterSetter('$$path', function(path) {
    path = path !== null ? path.toString() : '';
    return path.charAt(0) == '/' ? path : '/' + path;
  }),