如何使用AngularJS获取url参数

如何使用AngularJS获取url参数

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>

这里变量locloc1返回测试作为上述URL的结果。这是正确的方法吗?


波斯汪
浏览 1077回答 3
3回答

撒科打诨

function&nbsp;GetURLParameter(parameter)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;url; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;search; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;parsed; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;count; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;loop; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;searchPhrase; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url&nbsp;=&nbsp;window.location.href; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;search&nbsp;=&nbsp;url.indexOf("?"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(search&nbsp;<&nbsp;0)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;""; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;searchPhrase&nbsp;=&nbsp;parameter&nbsp;+&nbsp;"="; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parsed&nbsp;=&nbsp;url.substr(search+1).split("&"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count&nbsp;=&nbsp;parsed.length; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(loop=0;loop<count;loop++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(parsed[loop].substr(0,searchPhrase.length)==searchPhrase)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;decodeURI(parsed[loop].substr(searchPhrase.length)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;""; &nbsp;&nbsp;&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP