18

网址可能是

person/show/31586

或者

person/show/31586#tab1

是否有可能以角度方式获取 ID?路由不是由角度管理的。上面的 url 加载了一个页面,只有页面上的一些内容是由 angular 管理的。

4

3 回答 3

33

$location服务从浏览器地址栏中解析 URL,并使该 URL 可用于您的应用程序。因为您使用的是常规 URL 路径和搜索段,所以您必须html5Mode使用$locationProvider.

默认情况下,$locationProvider使用 hashbangs,所以如果你不设置html5Mode为 true,当你尝试获取 URL 路径时,你会得到一个空字符串。

设置好之后html5mode,就可以使用$location服务来获取 URL 路径,并编写自己的规则来处理路径。

例如,假设您的完整 URL 如下所示:http://example.com/person/show/321

那么main.js你可能有:

angular.module("MyAPP",[],function($locationProvider){
    $locationProvider.html5Mode(true);
});

function MainController($location){
    var pId = $location.path().split("/")[3]||"Unknown";    //path will be /person/show/321/, and array looks like: ["","person","show","321",""]
    console.log(pId);
}

index.html可能有:

<!DOCTYPE html>
<html lang="en" ng-app="MyAPP">
    <head>
        <meta charset="utf-8">
        <title>Angular test</title>
    </head>
    <body ng-controller="MainController">
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

希望这对你有帮助。

于 2013-08-07T08:59:42.540 回答
13

如果你想得到字符串的最后一段,你可以做这样的事情

function MainController($location){
   var pId = $location.path().split(/[\s/]+/).pop();
     console.log(pId);         //321
}
于 2015-06-06T23:27:41.733 回答
1

万一其他人来到这里寻求与在 Angular 中检索 url 相关的帮助。有时,可能需要访问absUrl

console.log($location.absUrl());
http://127.0.0.1:3000/home
于 2017-01-05T01:57:26.350 回答