Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally append a query string to an angular href

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?

like image 325
John Avatar asked Dec 16 '14 19:12

John


3 Answers

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 ? ...)+'...';
like image 143
Sn0opr Avatar answered Sep 30 '22 09:09

Sn0opr


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.

like image 22
New Dev Avatar answered Sep 30 '22 10:09

New Dev


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";
}
like image 28
JJ Zabkar Avatar answered Sep 30 '22 08:09

JJ Zabkar