我想使用AngularJS读取URL查询参数的值。我使用以下URL访问HTML:
http://127.0.0.1:8080/test.html?target=bob
不出所料,location.search
是"?target=bob"
。为了访问target的值,我在web上找到了各种示例,但它们都不适用于AngularJS 1.0.0rc10。具体地说,下面是所有undefined
$location.search.target
$location.search['target']
$location.search()['target']
谁知道什么能行得通吗?(我使用$location
作为控制器的参数)
更新:
我在下面发布了一个解决方案,但我对它并不完全满意。Developer Guide: Angular Services: Using $location上的文档介绍了以下有关$location
的内容
什么时候应该使用$location?
任何时候您的应用程序需要对当前URL中的更改做出反应,或者您希望在浏览器中更改当前URL。
对于我的场景,我的页面将从带有查询参数的外部网页打开,因此我本身并不是“对当前URL中的更改做出反应”。因此,也许$location
不是适合这项工作的工具(关于丑陋的细节,请参阅下面的答案)。因此,我将这个问题的标题从“如何使用$location在AngularJS中读取查询参数?”修改为“在AngularJS中读取查询参数的最简洁方法是什么?”显然,我可以只使用javascript和正则表达式来解析location.search
,但是对于如此基本的东西进行如此低级的解析确实冒犯了我的程序员的敏感性。
那么:有没有比我的回答更好的方式来使用$location
,或者有没有一个简洁的替代方法?
发布于 2012-06-16 22:57:18
您可以将$routeParams (需要ngRoute)注入到控制器中。下面是文档中的一个示例:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
编辑:您还可以使用$location服务(在ng
中可用)获取和设置查询参数,特别是它的search
方法:$location.search()。
在控制器初始加载之后,$routeParams就没那么有用了;$location.search()
可以随时调用。
发布于 2012-07-17 01:56:49
很好,你已经设法让它在html5模式下工作,但也可以让它在hashbang模式下工作。
您可以简单地使用:
$location.search().target
来访问“target”搜索参数。
作为参考,下面是工作jsFiddle:http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $location) {
$scope.location = $location;
$scope.$watch('location.search()', function() {
$scope.target = ($location.search()).target;
}, true);
$scope.changeTarget = function(name) {
$location.search('target', name);
}
}
<div ng-controller="MyCtrl">
<a href="#!/test/?target=Bob">Bob</a>
<a href="#!/test/?target=Paul">Paul</a>
<hr/>
URL 'target' param getter: {{target}}<br>
Full url: {{location.absUrl()}}
<hr/>
<button ng-click="changeTarget('Pawel')">target=Pawel</button>
</div>
发布于 2012-06-17 14:37:15
为了部分回答我自己的问题,这里有一个适用于HTML5浏览器的工作示例:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script>
angular.module('myApp', [], function($locationProvider) {
$locationProvider.html5Mode(true);
});
function QueryCntl($scope, $location) {
$scope.target = $location.search()['target'];
}
</script>
</head>
<body ng-controller="QueryCntl">
Target: {{target}}<br/>
</body>
</html>
关键是像上面那样调用$locationProvider.html5Mode(true);
。它现在可以在打开http://127.0.0.1:8080/test.html?target=bob
时使用。我对它不能在旧浏览器中工作这一事实感到不高兴,但无论如何我可能会使用这种方法。
一种适用于较旧浏览器的替代方法是删除html5mode(true)
调用,并在hash+slash中使用以下地址:
http://127.0.0.1:8080/test.html#/?target=bob
相关文档在Developer Guide: Angular Services: Using $location (奇怪的是我的谷歌搜索没有找到这个……)。
https://stackoverflow.com/questions/11063673
复制相似问题