如何用angular js对HTML元素的id属性进行条件设置

How to conditional set the id attribute of a HTML element with angular js?

本文关键字:属性 id 设置 条件 元素 angular 何用 js HTML      更新时间:2023-09-28

我想有条件地设置HTML元素的id属性。

简单方法:

<!--  expression = true -->
<div ng-if="expression"> 
  <a href id="this-one">Anchor with id</a>
</div>
<div ng-if="!expression">
  <a href>Anchor without id</a>
</div>
output-if-expression-true = <a href id="this-one">Anchor with id</a>
output-if-expression-false= <a href>Anchor without id</a>

我可以用类似三元运算符的东西来避免这种情况吗?例如

<a href ng-attr-id="{{expresion ? 'this-one': ''}}">Anchor</a>

如果你已经知道答案,为什么要问:-)?试试看,它确实是

<a href ng-attr-id="{{expresion ? 'this-one': ''}}">Anchor</a>

上面的解决方案对我不起作用

id="{{expression ? 'this-one': 'that-one'}}"