6

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?

3 Answers 3

3

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 ? ...)+'...';
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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";
}

2 Comments

FWIW: I think my answer has a declarative & semantic advantage over @Sn0opr's: By indicating that it's a function in your ng-href, you're declaring "this is not some static variable". Using a $scope variable hides that semantic difference. As for the $watch performance, it's unlikely that a URL would change with such frequency to impact $watch significantly.
But this doesn't actually work. ng-href only supports templates while this uses an expression. If you do this the href will literally be "getQueryUrl()" as opposed to some value that the function would've returned had it been called.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.