如何使用AngularJS获取url参数

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> 

这里variableslocloc1都返回testing结果作为上面的URL。 这是正确的方法吗?

我知道这是一个古老的问题,但考虑到稀疏的Angular文档,我花了一些时间来解决这个问题。 RouteProviderrouteParams是要走的路。 路由将URL连接到Controller / View,并且routeParams可以传递到控制器。

查看Angular种子项目。 在app.js中你会find一个路由提供者的例子。 要使用参数,只需将它们附加到像这样:

 $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; ... }]); 

虽然路由确实是应用程序级URLparsing的一个很好的解决scheme,但您可能希望使用更低级别的$location服务,如注入到您自己的服务或控制器中:

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

这个简单的语法将适用于http://example.com/path?myParam=paramValue 。 但是,只有在以下情况下以HTML 5模式configuration$locationProvider

 $locationProvider.html5Mode(true); 

否则,请查看http://example.com/#!/path?myParam=someValue“Hashbang ”语法,该语法稍微复杂一些,但可以在旧版浏览器(与HTML 5不兼容)上使用好。

如果您使用ngRoute,则可以将$routeParams注入到控制器中

http://docs.angularjs.org/api/ngRoute/service/$routeParams

如果你使用angular-ui-router,你可以注入$stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

如果已经发布的答案没有帮助,可以尝试使用$ location.search()。myParam; URL为http://example.domain#?myParam = paramValue