格式化可选的查询参数一个外部链接 [英] Formatting an external link with optional query params
问题描述
我工作的一个角应用需要与属于角页本身上设置一些查询参数链接到一个固定的(外部)路由。我想提供某种形式的漂亮数据绑定在我的角度HTML,如:
I'm working on an Angular app that needs to link to a fixed (external) route with some query params that are set on the Angular page itself. I'd like to provide some sort of nice data-binding in my Angular HTML, like:
<a href="http://www.api.com/query?param={{value}}&flag={{check}}">Link</a>
不过,我所有的查询参数都是可选的。这是很容易的角度应用程序本身内处理,使用类似
However, all my query parameters are optional. This is easily handled within an Angular app itself, using something like
$location.path('/query').search({param: value, flag: check});
有什么办法,我可以得到这个声明风格带来的好处时,我只是想格式化文本链接?
Is there any way I can get the benefits of this declarative style when I just want to format a text link?
推荐答案
我意识到,这个理想的机制可能是一个的过滤。它利用自动数据绑定和非常简单易用。该HTML变为:
I realised that the ideal mechanism for this is probably a filter. It leverages automatic data-binding and is really simple to use. The HTML becomes:
<a ng-href="http://www.api.com/endpoint{{params | query}}">Link</a>
和过滤器code:
myApp.filter('query', function() {
return function(opts) {
var params = [];
for(var opt in opts) {
if(opts.hasOwnProperty(opt)) {
if(opts[opt] !== "" && opts[opt] !== undefined) {
params.push(opt + "=" + opts[opt]);
}
}
}
return params.length
? "?" + params.join("&")
: "";
};
});
和这里有一个小提琴。该过滤器手柄未定义
属性和空字符串...完美的为我所用,如此,但我意识到这可能不是适合每一个人。无论如何,过滤器code本身是pretty简单的修改(你可以很容易地的 $。参数
如果适合你)。
And here's a fiddle. This filter handles undefined
properties and empty strings... perfect for my own use-case but I realise it might not be for everyone. Anyway, the filter code itself is pretty simple to modify (and you could easily replace it with $.param
if that suits you).
编辑:我既然意识到AngularJS设置绑定到一个空的输入模式,以空
,所以在我的实际code我检查对空
中的过滤器。
I've since realised that AngularJS sets models bound to an empty input to null
, so in my actual code I'm checking against null
in the filter.
这篇关于格式化可选的查询参数一个外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!