如何使用AngularJS获取url参数
HTML source code
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 source code
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>
Here the variables loc
and loc1
both return test as the result for the above URL. Is this the correct way?
在这里,变量loc和loc1都返回测试作为上述URL的结果。这是正确的方法吗?
5 个解决方案
#1
297
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.
我知道这是一个老问题,但我花了一些时间来整理这个问题,考虑到稀疏的角度文档。航线提供商和航线提供商是一条可行之路。路由将URL连接到您的控制器/视图,并可以将routeParams传递到控制器。
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:
看看角种子项目。在app.js中,您将为路由提供程序找到一个示例。要使用params,只需如下所示:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
然后在控制器中注入$routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);