简体   繁体   中英

Get dynamic query string paramters from URL - AngularJS

I've an URL where the query string parameters are dynamic. I need to read them in my JavaScript. What I've done is

I've used the following code to read all the query string parameters.

For example:

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var searchObject = $location.search();
// searchObject  => {foo: 'bar', baz: 'xoxo'}

I also have an array with the keys. Here my array will have foo and baz .

For example: var list = ["foo", "baz"];

So how do I get the values from the URL with the keys I've in my list array?

I tried this way

for(var i=0; i<list.length; i++)
                {
                    alert(searchObject.list[i]);
                }

But this gave me an Error in the console searchObject.list is undefined.

What am I doing wrong here? Can someone help?

Try

for(var i=0; i<list.length; i++)
{
    alert(searchObject[list[i]]);
}

I'm not sure why you have included the list property, searchObject is just and (as the name suggests) a plain old javascript object.

This should be what you want:

for(var i=0; i<list.length; i++) {
    alert(searchObject[list[i]]);
}

Loop though the items of list, using each one as the key to the searchObject object.

http://jsfiddle.net/8vekqezj/

May be using the AngularJS utility:

angular.forEach(list, function(key){
  alert(searchObject[key]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM