Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - 如何使用AngularJS获取url参数(How to get the url parameters using AngularJS)

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.

(在这里,变量locloc1都返回test作为上述URL的结果。)

Is this the correct way?

(这是正确的方法吗?)

  ask by praveenpds translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation.

(我知道这是一个老问题,但是鉴于稀疏的Angular文档,我花了一些时间来解决这个问题。)

The RouteProvider and routeParams is the way to go.

(RouteProviderrouteParams是必经之路。)

The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

(路由将URL连接到您的Controller / View,并且routeParams可以传递到控制器中。)

Check out the Angular seed project.

(签出Angular种子项目。)

Within the app.js you'll find an example for the route provider.

(在app.js中,您将找到路由提供者的示例。)

To use params simply append them like this:

(要使用参数,只需将它们附加如下:)

$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;
  ...
}]);

With this approach you can use params with a url such as: " http://www.example.com/view1/param1/param2 "

(通过这种方法,您可以将参数与URL一起使用,例如:“ http://www.example.com/view1/param1/param2 ”)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...