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源代码

<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的结果。这条路对吗?


当前回答

我发现解决方案如何使用$location.search()从URL获取参数

首先在URL中,你需要把语法“#”放在参数之前,就像这个例子一样

“http://www.example.com/page ?键=值”

然后在你的控制器你把$location函数和使用$location.search()获取URL参数

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);

其他回答

如果你正在使用ngRoute,你可以在你的控制器中注入$routeParams

http://docs.angularjs.org/api/ngRoute/service/ routeParams美元

如果你在使用angular-ui-router,你可以注入$stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

简单和简单的方法获得url值

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"

我知道这是一个老问题,但考虑到Angular文档很少,我花了一些时间来解决这个问题。RouteProvider和routeParams是正确的方法。路由将URL连接到控制器/视图,routeParams可以传递给控制器。

查看Angular种子项目。在app.js中,你会发现一个路由提供程序的例子。要使用参数,只需像这样添加参数:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: '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”

在路由器中:

url: "/login/reset_password/:user/:token"

在你的控制器中:

let userParam = $state.params.user
let tokenParam = $state.params.token

我发现解决方案如何使用$location.search()从URL获取参数

首先在URL中,你需要把语法“#”放在参数之前,就像这个例子一样

“http://www.example.com/page ?键=值”

然后在你的控制器你把$location函数和使用$location.search()获取URL参数

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);