AngularJS; Parse Current URL PathName to Pull Out Parameters

728 views
Skip to first unread message

Cody Carlson

unread,
Feb 11, 2014, 5:54:02 PM2/11/14
to ang...@googlegroups.com
Hi,

I need to be able to pass a URL pathName to a function and have it return the parameters for that path.

var myPath = '/locations/998/search/recipes';

var paramsObject = someAngularFunction(myPath);

console.log('Params for this path are:', paramsObject);
=> { storeId: '998', category: 'recipes' }

Basically, just as the $routeProvider can parse the URL and pull out the ":storeId" and ":category" parameters, I need a method which can pull these out.

Much appreciation,

Cody

Luke Kende

unread,
Feb 12, 2014, 12:59:40 AM2/12/14
to ang...@googlegroups.com
So... why can't just get it from $routeParams?

If there's something non-angular that you need, you can always access the window.location object and parse the path your self.

Guntram Pollock

unread,
Feb 12, 2014, 6:29:51 AM2/12/14
to ang...@googlegroups.com
how about some regexping:

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

Sander Elias

unread,
Feb 12, 2014, 6:34:11 AM2/12/14
to ang...@googlegroups.com
Hi Cody,

Did you look into $location, I think most of what you need is solved in there!

Regards
Sander

Cody Carlson

unread,
Feb 13, 2014, 2:41:05 PM2/13/14
to ang...@googlegroups.com
Well, I need it inside of `app.run` which always returns an empty object. Right now I'm just getting $location.path() and running a .split('/') and then checking the indices that I "know" will be in those URI namespaces. Clugy.

Cody Carlson

unread,
Feb 13, 2014, 2:49:19 PM2/13/14
to ang...@googlegroups.com
Hi Sander,

I looked into $location. I basically need to do a '$location.getParams('/locations/998/search/recipes')' that will give me back the same type of object $routeParams does --
-- meaning, if the URI has "998" as "storeId" OR if the window.location search looks like "?storeId=998", it should still give me back an object like that of $routeParams ($routeParams does this).

Is it possible to extract $routeParams from a $location URL?

Cody Carlson

unread,
Feb 13, 2014, 3:02:01 PM2/13/14
to ang...@googlegroups.com
Et Al,

I came up with roughly the solution I was looking for. As some mentioned, " why not use '$routeParams' " and I replied that it was an empty object literal always -- that's not true. I was using $on('$routeChangeStart', ...) when I should have been using '$routeChangeSuccess'. I now have:


  app.run(function($rootScope, $routeParams, $route, $location, $http){
    $rootScope.$on('$routeChangeSuccess', function(next, prev){
    ...
...

and I am getting the $routeParams I am looking for.

All the help and insight and time from you guys is much appreciated.

Cheers :)

Cody

On Tuesday, February 11, 2014 3:54:02 PM UTC-7, Cody Carlson wrote:
Reply all
Reply to author
Forward
0 new messages