且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 AngularJS $location 从 URL 中的查询字符串获取值

更新时间:2023-02-24 10:10:10

不确定自从接受的答案被接受后是否发生了变化,但有可能.

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() 将返回一个键值对对象,与查询字符串相同.没有值的键只是作为 true 存储在对象中.在这种情况下,对象将是:

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

您可以直接使用 $location.search().test_user_bLzgB

示例(带有更大的查询字符串):http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

注意:由于散列(因为它将转到 http://fiddle.jshell.net/#/url,这将创建一个新的小提琴),这个小提琴在不支持 js 历史的浏览器中不起作用(在 IE <10 中不起作用)

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)


正如@Naresh 和@DavidTchepak 在评论中指出的,$locationProvider 也需要正确配置:https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration