从参数对象构建查询字符串

bsr*_*bsr 76 javascript querystringparameter angularjs

如何在Angularjs中使用查询参数构建URL.

我看到API $ location.search()

问题是$ location(url)是重定向到url.在我的例子中,我想为查询参数传递url和key:value对并​​构建url.就像是

url:/a/b/c params:{field1: value1, field2: value2}

结果: /a/b/c?field1=value1&field2=value2

我喜欢用这个网址链接.我也见过角度编码?,&字符.我可以避免这个吗?

编辑:

我的目的是使用url作为锚元素的href.我确实使用$ http来发送请求,但有时我需要提供一个链接,带有查询参数(基于当前对象)

谢谢

Arm*_*ier 123

从1.4+开始,有一个很好的解决方案.您可以使用以下参数从参数对象构建查询字符串$httpParamSerializer:

var qs = $httpParamSerializer(params);
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档

默认的$ http params序列化程序,它根据以下规则将对象转换为字符串:

{'foo': 'bar'} results in foo=bar
{'foo': Date.now()} results in foo=2015-04-01T09%3A50%3A49.262Z (toISOString() and encoded representation of a Date object)
{'foo': ['bar', 'baz']} results in foo=bar&foo=baz (repeated key for each array element)
{'foo': {'bar':'baz'}} results in foo=%7B%22bar%22%3A%22baz%22%7D" (stringified and encoded representation of an object)
Note that serializer will sort the request parameters alphabetically.
Run Code Online (Sandbox Code Playgroud)


sho*_*one 14

Angular在buildUrl()内部使用该函数从参数对象生成查询字符串.现在,在你的代码中使用它是不可能的,因为它是私有的,$HttpProvider除非你想做一些eval()魔术.

github上的相关问题: