如何使用AngularJS获取url参数 [英] How to get the url parameters using AngularJS
问题描述
HTML 源代码
<div ng-controller="测试"><div ng-address-bar browser="html5"></div><br><br>$location.url() = {{$location.url()}}
$location.search() = {{$location.search('keyword')}}<br>$location.hash() = {{$location.hash()}}
关键字值是={{loc}} 和={{loc1}}
AngularJS 源代码
这里的变量 loc
和 loc1
都返回 test 作为上述 URL 的结果.这是正确的方法吗?
我知道这是一个老问题,但鉴于 Angular 文档很少,我花了一些时间来解决这个问题.RouteProvider 和 routeParams 是要走的路.路由将 URL 连接到您的控制器/视图,并且可以将 routeParams 传递到控制器中.
查看 Angular 种子 项目.在 app.js 中,您将找到路由提供程序的示例.要使用参数,只需像这样附加它们:
$routeProvider.when('/view1/:param1/:param2', {templateUrl: 'partials/partial1.html',控制器:'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">
HTML source code
<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 source code
<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>
Here the variables loc
and loc1
both return test as the result for the above URL. Is this the correct way?
I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"
这篇关于如何使用AngularJS获取url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!