Conditionally add a query string to angular href

I create some links in AngularJS v1.2.16 as follows:

<a ng-href="/foo/{{id}}/t/{{list[m].id}}/{{id2}}/{{otherId}}">Click here!</a>

This works great.

Now I have a query parameter querythat I would like to add at the end, if it exists.

I tried to do it like this:

<a ng-href="/foo/{{id}}/{{otherId}}{{ query ? '?q=' + query : "" }}">Click here!</a>

The result is the following, because angular simply maps the entire contents of the tag to the link like this:

<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 am trying to do?

+4
source share
3 answers

To answer your specific question, your attempt did not work because you used double quotes ""inside other double quotes. Change <a>to the following and it will work:

<a ng-href="/foo/{{id}}/{{otherId}}{{ query ? '?q=' + query : '' }}">Click here!</a>

- ( , URL) , .

+1

url , , ,

<a ng-href="{{myUrl}}">Click here!</a>

:

$scope.myUrl = 'foo/'+id+'/.../'+(qry ? ...)+'...';
+3

I would build the url in the controller.

HTML

<a ng-href="getQueryUrl()">Click here!</a>

Controller.js

$scope.getQueryUrl = function getQueryUrlFn(){
   return "/foo/bar?query=abc";
}
+1
source

All Articles