有条件的查询字符串追加到角HREF有条件、字符串、HREF

2023-09-13 04:47:27 作者:Garbage

我建设AngularJS v1.2.16像这样的一些链接:

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>

这伟大工程。

现在我有一个查询参数查询我要追加到结束时,如果它的存在。

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?

推荐答案

要回答你的具体问题,你的企图没有工作,因为你已经使用双引号内的其他双引号。更改&LT; A&GT; 以下,也将努力:

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>

不过,我同意其他的答案 - 有时它的更好,更洁净生成控制器中的值(在这种情况下,URL),特别是如果你想建立一个围绕该值的单元测试。

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.