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 badges
Add a ment  | 

3 Answers 3

Reset to default 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 ? ...)+'...';

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