获取AngularJS中的部分网址

Upv*_*ote 18 javascript angularjs

网址可能是

person/show/31586
Run Code Online (Sandbox Code Playgroud)

要么

person/show/31586#tab1
Run Code Online (Sandbox Code Playgroud)

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

Chi*_*ice 33

$location服务从浏览器地址栏解析URL,并使URL可用于您的应用程序.由于您使用的是常规网址路径和搜索细分,因此必须将其设置html5Mode为true $locationProvider.

默认情况下,$locationProvider使用hashbangs,因此如果未设置html5Mode为true,则在尝试获取URL路径时将获得空字符串.

设置后html5mode,您可以使用该$location服务获取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);
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助.


小智 13

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

function MainController($location){
   var pId = $location.path().split(/[\s/]+/).pop();
     console.log(pId);         //321
}
Run Code Online (Sandbox Code Playgroud)