如何以编程方式使用AngularJS创建网址 [英] How to programmatically create URLs with AngularJS
问题描述
现在我想在我的应用程序中导航,比如说,通过更改搜索当前网址的一部分。在JavaScript中使用$ location服务很容易,但是如何在当前路由中构建一个href属性并替换搜索部分?
我有或者是否有AngularJS的方式?
新增:
当然,$ location服务有所有计算这种URL的方法。但我无法使用它,因为$ location也会将浏览器窗口导航到新的URL。
手工创建URL还有一个复杂性:必须检查传统#方法或新的历史API被使用。根据这个,URL必须包含一个#号或不是。
从v1.4开始,您可以使用< href =https://docs.angularjs.org/api/ng/service/$httpParamSerializer> $ httpParamSerializer :
var serializedParams = $ httpParamSerializer('util' params);
if(serializedParams.length> 0){
url + =((url.indexOf('?')=== -1)?'?':' &')+ serializedParams;
}
return url;
}
return buildUrl;
});
使用:
制作 http:// url?param1 = value1& param2 = value2_1& param2 = value2_2
用以下方式调用它:
urlBuilder('http:// url',{param1:'value1',param2:['value2_1','value2_2']});
Currently I am toying with the AngularJS framework. I'm using the $route service for deep linking into my single-page application.
Now I would like to navigate inside my application, say, by changing just the search part of the current URL. It is easy to do using the $location service in JavaScript, but how can I construct an href attribute from the current route with just the search part replaced?
Do I have to do it by hand or is there an AngularJS way for it?
Added:
Of course, the $location service has all methods to calculate such URLs. But I cannot use it because $location does also navigate the browser window to the new URL.
There is another complication with creating URLs by hand: One has to check whether the legacy #-method or the new History API is used. Depending on this, the URL has to include a #-sign or not.
Starting from v1.4 you can use $httpParamSerializer for that:
angular.module('util').factory('urlBuilder', function($httpParamSerializer) {
function buildUrl(url, params) {
var serializedParams = $httpParamSerializer(params);
if (serializedParams.length > 0) {
url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
}
return url;
}
return buildUrl;
});
Usage:
To produce http://url?param1=value1¶m2=value2_1¶m2=value2_2
call it with:
urlBuilder('http://url', { param1: 'value1', param2: ['value2_1', 'value2_2'] });
这篇关于如何以编程方式使用AngularJS创建网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!