如何使用AngularJS获取URL参数

207

HTML源代码

<div ng-app="">
    <div ng-controller="test">
      <div ng-address-bar browser="html5"></div>
      <br><br>
      $location.url() = {{$location.url()}}<br>
      $location.search() = {{$location.search('keyword')}}<br>
      $location.hash() = {{$location.hash()}}<br>     
      keyword valus is={{loc}} and ={{loc1}}
  </div>
</div>

AngularJS源代码

<script>
function test($scope, $location) {
  $scope.$location = $location;
  $scope.ur = $scope.$location.url('www.html.com/x.html?keyword=test#/x/u');
  $scope.loc1 = $scope.$location.search().keyword ;    
    if($location.url().indexOf('keyword') > -1){    
        $scope.loc= $location.url().split('=')[1];
        $scope.loc = $scope.loc.split("#")[0]        
    }
  }
 </script>

这里变量 locloc1 对于上述URL都返回 test 作为结果。这是正确的方式吗?


1
你可能想要查看$routeParams - Nick Heiner
不清楚你在这里问什么... $routeParams 和 $location#methods 的文档应该可以帮助你入门。 - deck
7
请在投票反对时考虑添加评论,以便改进问题。谢谢。 - praveenpds
9个回答

320
我知道这是一个旧的问题,但在稀疏的Angular文档中花费了一些时间才弄清楚。 RouteProviderrouteParams 是正确的方法。路由将URL连接到您的Controller/View,而routeParams可以传递到控制器中。
请查看Angular seed 项目。在app.js中,您将找到一个route provider的示例。要使用params,只需像这样添加它们:
$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'
});

然后在您的控制器中注入 $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;
  ...
}]);

使用这种方法,您可以将参数与URL一起使用,例如:http://www.example.com/view1/param1/param2


2
请注意,此示例的最后一行});应为}]); - Andrew Lank
45
还可以通过 /view/1/2?other=12 的查询字符串获取其他任意参数,使用 $routeParams.other - DavidC
我认为你的控制器中重复了'var param1'。我无法编辑这样一个简单的改变。 - Tom
Angular 让它变得如此简单,而且你的答案也非常详细。 - Mohammad Kermani
1
赋值并发送示例:var param1 = "abc"; $location.path('/view1/:' + param1);$route.reload(); - Robot70
如果你有多个前端路由,这很棒,但如果你只想解析参数,那就过于复杂了。 - jiminikiz

169

虽然路由确实是用于应用级别URL解析的好方案,但您可能希望使用更低级别的$location服务,将其注入到您自己的服务或控制器中:

var paramValue = $location.search().myParam; 

这个简单的语法适用于 http://example.com/path?myParam=paramValue。但前提是您在HTML 5模式下配置了$locationProvider

$locationProvider.html5Mode(true);
否则,请查看“Hashbang”语法,该语法位于http://example.com/#!/path?myParam=someValue,这种语法有点复杂,但它可以在旧浏览器上(非HTML 5兼容)使用的好处。

16
似乎您需要将$locationProvider.html5mode(true)添加为模块配置,如下所示:angular.module("myApp", [])。 config(function($locationProvider) { $locationProvider.html5Mode(true); }); - sq1020
4
html5Mode需要在您的index.html文件中添加一个<base href="http://example.com/en/" />标签。此操作旨在确保路由正确解析为基于http://example.com/en/的URL。 - cespon
1
我喜欢你的解决方案的原因是,甚至可以传递对象,并将其作为对象获取。 - Shilan
3
也可以不添加<base>标签,而是像这样指定: .config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }); }]) - Guillaume
1
在Angular 1.5.8中,我不需要配置$locationProvider就可以使其工作。http://example.com/path#?someKey=someVal,然后$location.search().someKey // => 'someVal' - jiminikiz

32

1
为了让$stateParams显示查询参数,我在定义状态时必须指定它们,如https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters中所示。 - Parziphal

14

我找到了如何使用 $location.search() 获取 URL 参数的解决方案。

首先,在 URL 中您需要在参数前加上语法“#”,就像这个示例一样:

"http://www.example.com/page#?key=value"

然后,在您的控制器中,将 $location 放入函数中,并使用 $location.search() 获取 URL 参数。

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);

它适用于查询参数,@jeff的下面答案适用于路径变量。 - Abdeali Chandanwala

2

1
这是此处第二高票解决方案...并且比这个发布了3年... https://dev59.com/omgt5IYBdhLWcg3w3xIw#19481865 - JustCarty

2
function GetURLParameter(parameter) {
        var url;
        var search;
        var parsed;
        var count;
        var loop;
        var searchPhrase;
        url = window.location.href;
        search = url.indexOf("?");
        if (search < 0) {
            return "";
        }
        searchPhrase = parameter + "=";
        parsed = url.substr(search+1).split("&");
        count = parsed.length;
        for(loop=0;loop<count;loop++) {
            if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
                return decodeURI(parsed[loop].substr(searchPhrase.length));
            }
        }
        return "";
    }

window.location.href 实际上是我在这种情况下所需要的。并不总是需要一些花哨的 Angular 解决方案。这对我很有用。 - Gishas

0

在你的路由器中:

url: "/login/reset_password/:user/:token"

在你的控制器中:

let userParam = $state.params.user
let tokenParam = $state.params.token

0

获取URL值的简单易用方法

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"

0

在使用angularjs和express时

在我的例子中,我使用angularjs和express进行路由,因此使用$routeParams会干扰我的路由。我使用以下代码来获得我期望的结果:

const getParameters = (temp, path) => {
  const parameters = {};
  const tempParts = temp.split('/');
  const pathParts = path.split('/');
  for (let i = 0; i < tempParts.length; i++) {
    const element = tempParts[i];
    if(element.startsWith(':')) {
      const key = element.substring(1,element.length);
      parameters[key] = pathParts[i];
    }
  }
  return parameters;
};

这个函数接收一个URL模板和给定位置的路径。我只需要这样调用它:

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path()); 

将所有内容放在一起,我的控制器是:

.controller('TestController', ['$scope', function($scope, $window) {
  const getParameters = (temp, path) => {
    const parameters = {};
    const tempParts = temp.split('/');
    const pathParts = path.split('/');
    for (let i = 0; i < tempParts.length; i++) {
      const element = tempParts[i];
      if(element.startsWith(':')) {
        const key = element.substring(1,element.length);
        parameters[key] = pathParts[i];
      }
    }
    return parameters;
  };

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);

结果将会是:

{ table: "users", id: "1", place_id: "43", interval: "week" }

希望这能帮助到某个人!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接