Search URL parameters with Angular JS

空扰寡人 提交于 2019-12-11 18:49:22

问题


Say I have a URL like this:

www.mysite.com?account=23&token=asdu756sdg65sdf

Now, I need to access those URL parameters individually using Angular JS.

I've tried using location.search inside my controller:

console.log(location.search);

Which nicely returns the full query string:

?account=23&token=asdu756sdg65sdf

But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?

I've also tried:

console.log($location.search());

Which seems to return an empty object.


回答1:


Try with

var account = ($location.search()).account;

but the url should be like /#!/?account=1




回答2:


have your tried using it as a function instead?

$location.search();




回答3:


pure js way:

var getParamFromURL = function(_url) {
    var url = _url;
    var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
    var _paraObj = {};
    for (i = 0; p = _paraString[i]; i++) {
        _paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
    }
    return _paraObj;
}

via angular js:

 // Given:
 // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
 // Route: /Chapter/:chapterId/Section/:sectionId
 //
 // Then
 $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}

Great. @Cooper is right.



来源:https://stackoverflow.com/questions/24981521/search-url-parameters-with-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!