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


当前回答

function GetURLParameter(parameter) {
        var url;
        var search;
        var parsed;
        var count;
        var loop;
        var searchPhrase;
        url = window.location.href;
        search = url.indexOf("?");
        if (search < 0) {
            return "";
        }
        searchPhrase = parameter + "=";
        parsed = url.substr(search+1).split("&");
        count = parsed.length;
        for(loop=0;loop<count;loop++) {
            if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
                return decodeURI(parsed[loop].substr(searchPhrase.length));
            }
        }
        return "";
    }

其他回答

在路由器中:

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

在你的控制器中:

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

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

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

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

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

我发现解决方案如何使用$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

}]);

简单和简单的方法获得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"

虽然路由确实是应用程序级URL解析的一个很好的解决方案,但你可能想要使用更低级的$location服务,就像注入到你自己的服务或控制器中一样:

var paramValue = $location.search().myParam; 

这个简单的语法适用于http://example.com/path?myParam=paramValue。然而,只有当你在HTML 5模式下配置了$locationProvider:

$locationProvider.html5Mode(true);

除此之外,还可以看看http://example.com/#!/path?myParam=someValue“Hashbang”语法,它稍微复杂一些,但也有在旧浏览器(非html 5兼容)上工作的好处。