Reputation: 37388
i use AngularJS with the angular-ui-router component for my Single-Page Website.
If i want to switch to another view (path) and add params, i can use $location.path() and $location.search() in combination like this:
$location.path('/foo/bar/').search('q','foobar');
Now i also need to generate Urls (i.e. to fill links on my site or to offer deep-link-here-directly links). So i have a service that generates and provides Urls based on user-input and state params.
Normally i would have the service provide something like /foo/bar/?q=foobar
, but then every time i want to set such a link with $location i would have to use string manipulation to strip away the GET params, call the original path and add the rest in .search().
var url = '/foo/bar/?q=foobar'
var tmpUrlParams = url.split('?')[1].split('&');
$location.path('url.split('?')[1]');
for (var i=0;i <= tmpUrlParams.length; i++){
$location.search(tmpUrlParams[i].split('=')[0], tmpUrlParams[i].split('=')[1]);
}
Is there a better solution for this? Well i know there is ... but what is it?
Upvotes: 2
Views: 361
Reputation: 44916
Perhaps I'm misunderstanding your question, but why can't you just use the url
method on $location
since it will correctly interpret your query string parameters?
//Calling $location.url()
$location.url('/somepath?foo=bar');
//Will result in these values
$location.url(); // '/somepath?foo=bar'
$location.path(); // '/somepath'
$location.search(); // '{"foo":"bar"}'
Here is an interactive jsFiddle you can use to play with and see the various values of the $location
api for yourself.
Upvotes: 3