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

时间:2013-09-06 20:11:07

标签: javascript angularjs querystringparameter

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

我看到了API $location.search()

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

之类的东西

网址:/a/b/c 参数:{field1: value1, field2: value2}

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

我喜欢将此网址用于链接。我还看到了角度编码?&个字符。我可以避免这个吗?

编辑:

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

由于

4 个答案:

答案 0 :(得分:120)

1.4+有一个很好的解决方案。您可以使用$httpParamSerializer

从参数对象构建查询字符串
var qs = $httpParamSerializer(params);

See docs here

  

默认的$ 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.

答案 1 :(得分:14)

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

github上的相关问题:

答案 2 :(得分:3)

相信你真的有点吠叫错误的树...你需要看看$ http服务,它给你$ http.get(url,config)或$ http.post(url,data,config )。有关带参数的GET请求,请参阅以下SO

$http get parameters does not work

有关$ http及其工作原理的信息,请参阅Angular文档。

http://docs.angularjs.org/api/ng.$http

也许我误解了目标但你实际上想要导航到另一个地方,我建议这里只是为了在后台提出请求(AJAX风格)。

http://jsfiddle.net/4ZcUW/

JS

angular.module("myApp", []).controller("MyCtrl", ["$scope", "$window", function($scope, $window) {
    $scope.goPlaces = function(url, parameter) {
        $window.open("http://www."+url+"?q="+parameter);
        //$window.open("http://www."+url+"?q="+parameter, "_self");
        //$window.open("http://www."+url+"?q="+parameter, "_top");
    };
}])

HTML

<div ng-app="myApp" ng-controller="MyCtrl">
    <a href="#" ng-click="goPlaces('google.com','Shaun Husain')">Find me</a>
</div>

这适用于您的情况吗?

答案 3 :(得分:0)

angular的内部和外部网址格式规则略有不同。

$ location是一种在您自己的应用程序中激活内部路线的方法。

如果是外部链接,那么$ http就是你想要的。

如果它是内部链接,那么检查可能值得检查hash / bang语法。