What's the most concise way to read query para

2019-01-03 11:34发布

I'd like to read the values of URL query parameters using AngularJS. I'm accessing the HTML with the following URL:

http://127.0.0.1:8080/test.html?target=bob

As expected, location.search is "?target=bob". For accessing the value of target, I've found various examples listed on the web, but none of them work in AngularJS 1.0.0rc10. In particular, the following are all undefined:

  • $location.search.target
  • $location.search['target']
  • $location.search()['target']

Anyone know what will work? (I'm using $location as a parameter to my controller)


Update:

I've posted a solution below, but I'm not entirely satisfied with it. The documentation at Developer Guide: Angular Services: Using $location states the following about $location:

When should I use $location?

Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.

For my scenario, my page will be opened from an external webpage with a query parameter, so I'm not "reacting to a change in the current URL" per se. So maybe $location isn't the right tool for the job (for the ugly details, see my answer below). I've therefore changed the title of this question from "How to read query parameters in AngularJS using $location?" to "What's the most concise way to read query parameters in AngularJS?". Obviously I could just use javascript and regular expression to parse location.search, but going that low-level for something so basic really offends my programmer sensibilities.

So: is there a better way to use $location than I do in my answer, or is there a concise alternate?

11条回答
孤傲高冷的网名
2楼-- · 2019-01-03 12:08

To give a partial answer my own question, here is a working sample for HTML5 browsers:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', [], function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
    function QueryCntl($scope, $location) {
      $scope.target = $location.search()['target'];
    }
  </script>
</head>
<body ng-controller="QueryCntl">

Target: {{target}}<br/>

</body>
</html>

The key was to call $locationProvider.html5Mode(true); as done above. It now works when opening http://127.0.0.1:8080/test.html?target=bob. I'm not happy about the fact that it won't work in older browsers, but I might use this approach anyway.

An alternative that would work with older browsers would be to drop the html5mode(true) call and use the following address with hash+slash instead:

http://127.0.0.1:8080/test.html#/?target=bob

The relevant documentation is at Developer Guide: Angular Services: Using $location (strange that my google search didn't find this...).

查看更多
Viruses.
3楼-- · 2019-01-03 12:09

I found that for an SPA HTML5Mode causes lots of 404 error problems, and it is not necessary to make $location.search work in this case. In my case I want to capture a URL query string parameter when a user comes to my site, regardless of which "page" they initially link to, AND be able to send them to that page once they log in. So I just capture all that stuff in app.run

$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
    if (fromState.name === "") {
        e.preventDefault();
        $rootScope.initialPage = toState.name;
        $rootScope.initialParams = toParams;
        return;
    }
    if ($location.search().hasOwnProperty('role')) {
        $rootScope.roleParameter = $location.search()['role'];
    }
    ...
}

then later after login I can say $state.go($rootScope.initialPage, $rootScope.initialParams)

查看更多
女痞
4楼-- · 2019-01-03 12:13

you could also use $location.$$search.yourparameter

查看更多
狗以群分
5楼-- · 2019-01-03 12:19

You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}

EDIT: You can also get and set query parameters with the $location service (available in ng), particularly its search method: $location.search().

$routeParams are less useful after the controller's initial load; $location.search() can be called anytime.

查看更多
做个烂人
6楼-- · 2019-01-03 12:22

this may help uou

What's the most concise way to read query parameters in AngularJS

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', [], function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
    function QueryCntl($scope, $location) {
      $scope.target = $location.search()['target'];
    }
  </script>
</head>
<body ng-controller="QueryCntl">

Target: {{target}}<br/>

</body>
</html>

($location.search()).target
查看更多
萌系小妹纸
7楼-- · 2019-01-03 12:24

Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode.

You could simply use:

$location.search().target

to get access to the 'target' search param.

For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/

var myApp = angular.module('myApp', []);

function MyCtrl($scope, $location) {

    $scope.location = $location;
    $scope.$watch('location.search()', function() {
        $scope.target = ($location.search()).target;
    }, true);

    $scope.changeTarget = function(name) {
        $location.search('target', name);
    }
}
<div ng-controller="MyCtrl">

    <a href="#!/test/?target=Bob">Bob</a>
    <a href="#!/test/?target=Paul">Paul</a>
    
    <hr/>    
    URL 'target' param getter: {{target}}<br>
    Full url: {{location.absUrl()}}
    <hr/>
    
    <button ng-click="changeTarget('Pawel')">target=Pawel</button>
    
</div>

查看更多
登录 后发表回答