问题描述
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源代码
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>
这里变量 loc
和 loc1
都返回 test 作为上述URL的结果。这是正确的方法吗?
Here the variables loc
and loc1
both return test as the result for the above URL. Is this the correct way?
推荐答案
我知道这是一个老问题,但我花了一些时间来解决这个问题。稀疏的Angular文档。 RouteProvider 和 routeParams 是可行的方法。路由将URL连接到Controller / View,并且routeParams可以传递到控制器。
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.
查看项目。在app.js中,您将找到路由提供程序的示例。要使用params,只需将它们添加如下:
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'
});
然后在你的控制器中注入$ routeParams:
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
这篇关于如何使用AngularJS获取url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!