2

I need to take as a parameter in my site's urls a file path (that will contain some number of '/' characters). How can I parse such a parameter from a url? Something like http://localhost/path/to/file would be preferable, but if that doesn't work, http://localhost/?path=/path/to/file or something could work as well.

alecbz
  • 6,292
  • 4
  • 30
  • 50
  • 1
    The former must be handled by your server using url rewrite rules. The latter can be done with the [`$location`](http://docs.angularjs.org/api/ng.$location) service. – Josh David Miller Mar 15 '13 at 06:39
  • 1
    @JoshDavidMiller How exactly are you supposed to use `$location`? I added it as a parameter to my controller and am printing `$location.url()` (via a function) in my view, but all I get is the empty string (when accessing, eg, `http://localhost:8000/?path=lol`) – alecbz Mar 15 '13 at 07:36
  • Same for `$location.search()`, just gives me an empty object as output. – alecbz Mar 15 '13 at 07:56
  • To access your `path` param using $location: `$location.search().path`. – Stewie Mar 15 '13 at 08:28
  • Like I said, `$location.search()` is an empty object for me when accessing `http://localhost:8000/?path=lol`. Is there anything I need to do other than have `$location` as a parameter to my controller to get it to work? – alecbz Mar 15 '13 at 16:35
  • Should work. You'll have to post a plunker. – Josh David Miller Mar 15 '13 at 17:11
  • http://pastie.org/6517877 The `stuff: {{ loc() | json }}` at the bottom always just appears as `stuff: {}` – alecbz Mar 15 '13 at 18:05
  • I get the same thing, and when I log $location, I get `{"$$protocol":"http","$$host":"localhost","$$port":5000,"$$path":"","$$search":{},"$$hash":"","$$url":"","$$absUrl":"http://localhost:5000/login.html?error=true"}`. Clearly it's parsing the URL, but why are the `url` and `search` parameters empty? – jab Apr 15 '13 at 20:46
  • See also [this question](http://stackoverflow.com/questions/16227004/how-to-capture-urls-with-arbitrary-number-of-slashes-in-angular-js) for essentially the same thing, but there the path part comes in the *angular* part of the URL, after the hash, so webserver-side rewrites should technically not be necessary. – nh2 Apr 26 '13 at 01:04
  • @nh2 That question doesn't have an answer, I provided a work around for the general idea but as far as I can tell you can't have an arbitrary number of slashes in the angular url. – lucuma Apr 26 '13 at 13:21

2 Answers2

0

to use location in your controller. first turn html5mode to true like this

Then you can use location.search and it will return string without any error. for more use of location go here https://docs.angularjs.org/api/ng/service/$location

Ankit Anand
  • 151
  • 1
  • 3
-1

Take a look at URI.js, it looks like what you need.