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?
It'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.
<a ng-href="getQueryUrl()">Click here!</a>
$scope.getQueryUrl = function getQueryUrlFn(){
return "/foo/bar?query=abc";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With