admin管理员组文章数量:1335871
I am building some links in AngularJS v1.2.16 like such:
<a ng-href="/foo/{{id}}/t/{{list[m].id}}/{{id2}}/{{otherId}}">Click here!</a>
That works great.
Now I have a query parameter query
I'd like to append to the end if it exists.
I tried to do it like so:
<a ng-href="/foo/{{id}}/{{otherId}}{{ query ? '?q=' + query : "" }}">Click here!</a>
I end up with the following, because angular just renders the entire contents to the tag into the link like so:
<a href="/foo/2/4%7B%7B%7B%20query%20?%20%27?q=%27%20+%query%20:">Click here!</a>
How can I achieve what I'm trying to do?
I am building some links in AngularJS v1.2.16 like such:
<a ng-href="/foo/{{id}}/t/{{list[m].id}}/{{id2}}/{{otherId}}">Click here!</a>
That works great.
Now I have a query parameter query
I'd like to append to the end if it exists.
I tried to do it like so:
<a ng-href="/foo/{{id}}/{{otherId}}{{ query ? '?q=' + query : "" }}">Click here!</a>
I end up with the following, because angular just renders the entire contents to the tag into the link like so:
<a href="/foo/2/4%7B%7B%7B%20query%20?%20%27?q=%27%20+%query%20:">Click here!</a>
How can I achieve what I'm trying to do?
Share Improve this question asked Dec 16, 2014 at 19:52 JohnJohn 3,9567 gold badges32 silver badges45 bronze badges3 Answers
Reset to default 3It's better to make a model for the url in the controller than making it like that, it will also avoid many $watch binding so better performance and cleaner
<a ng-href="{{myUrl}}">Click here!</a>
In the controller:
$scope.myUrl = 'foo/'+id+'/.../'+(qry ? ...)+'...';
To answer your specific question, your attempt didn't work because you have used double-quotes ""
inside other double-quotes. Change the <a>
to the following and it will work:
<a ng-href="/foo/{{id}}/{{otherId}}{{ query ? '?q=' + query : '' }}">Click here!</a>
But, I agree with the other answers - sometimes it's better and cleaner to generate a value (in this case, URL) in the controller, especially if you want to build a unit-test around this value.
I'd do the URL construction in the Controller.
HTML
<a ng-href="getQueryUrl()">Click here!</a>
Controller.js
$scope.getQueryUrl = function getQueryUrlFn(){
return "/foo/bar?query=abc";
}
本文标签: javascriptConditionally append a query string to an angular hrefStack Overflow
版权声明:本文标题:javascript - Conditionally append a query string to an angular href - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742394512a2466649.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论