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:27

It can be done by two ways:

  1. Using $routeParams

Best and recommended solution is to use $routeParams into your controller. It Requires the ngRoute module to be installed.

   function MyController($scope, $routeParams) {
      // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
      // Route: /Chapter/:chapterId/Section/:sectionId
      // $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
      var search = $routeParams.search;
  }
  1. Using $location.search().

There is a caveat here. It will work only with HTML5 mode. By default, it does not work for the URL which does not have hash(#) in it http://localhost/test?param1=abc&param2=def

You can make it work by adding #/ in the URL. http://localhost/test#/?param1=abc&param2=def

$location.search() to return an object like:

{
  param1: 'abc',
  param2: 'def'
}
查看更多
Root(大扎)
3楼-- · 2019-01-03 12:29

Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true); won't work with new version of angularjs without specifying the base URL for the application with a <base href=""> tag or setting the parameter requireBase to false

From the doc :

If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});
查看更多
够拽才男人
4楼-- · 2019-01-03 12:30

Just to summerize .

If your app is being loaded from external links then angular wont detect this as a URL change so $loaction.search() would give you an empty object . To solve this you need to set following in your app config(app.js)

.config(['$routeProvider', '$locationProvider', function ($routeProvider,     $locationProvider) 
{
   $routeProvider
      .when('/', {
         templateUrl: 'views/main.html',
         controller: 'MainCtrl'
      })
      .otherwise({
         redirectTo: '/'
      });

      $locationProvider.html5Mode(true);
 }]);
查看更多
贪生不怕死
5楼-- · 2019-01-03 12:32

$location.search() will work only with HTML5 mode turned on and only on supporting browser.

This will work always:

$window.location.search

查看更多
可以哭但决不认输i
6楼-- · 2019-01-03 12:33

It's a bit late, but I think your problem was your URL. If instead of

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

you had

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

I'm pretty sure it would have worked. Angular is really picky about its #/

查看更多
登录 后发表回答