我想用AngularJS来读取URL查询参数的值。 我正在用下面的URL访问HTML。
http://127.0.0.1:8080/test.html?target=bob
正如预期,location.search
是"?target=bob"
。
对于访问target的值,我在网上找到了各种列举的例子,但在AngularJS 1.0.0rc10中没有一个能用。 特别是,以下这些都是 "未定义 "的。
$location.search.target
。$location.search['target']
。$location.search()['target']
。有谁知道什么会有效?(我使用$location
作为我的控制器的一个参数)
更新。
我在下面发布了一个解决方案,但我对它并不完全满意。 开发者指南:Angular服务:使用$location]1的文档对"$location "有如下说明。
我应该在什么时候使用$location?
任何时候你的应用程序需要对当前URL的变化做出反应
如果你想改变浏览器中的当前URL。
对于我的情况,我的页面将从一个带有查询参数的外部网页打开,所以我没有对当前URL的变化做出反应。 因此,也许$location
并不是正确的工具(关于丑陋的细节,见我下面的回答)。因此,我把这个问题的标题从"如何在AngularJS中使用$location读取查询参数?"改为"在AngularJS中读取查询参数的最简洁的方法是什么?"。 显然,我可以使用javascript和正则表达式来解析location.search
,但对如此基本的东西进行如此低级的处理,实在有违我的程序员情怀。
那么:是否有比我的答案更好的方法来使用$location
,或者有一个简洁的替代方案?
你可以将$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()'可以随时调用。
很好,你已经设法让它在html5模式下工作,但也有可能让它在hashbang模式下工作。
你可以简单地使用。
$location.search().target
来获取'目标&39;搜索参数。
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>
<!--结束片段-->。
为了部分回答我自己的问题,这里有一个用于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
相关文档在开发者指南:Angular服务:使用$location(奇怪的是,我的谷歌搜索没有找到这个...)。