que1326
que1326

Reputation: 2325

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

I want to set the id attribute of a HTML element conditionally.

Simple way:

<!--  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>

Can I avoid this with something like a ternary operator ? for example ...

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

Upvotes: 8

Views: 29902

Answers (2)

a_lovelace
a_lovelace

Reputation: 500

The above solution didn't work for me. The following did:

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

Upvotes: 12

fikkatra
fikkatra

Reputation: 5792

Why do you ask if you already know the answer :-)? Try it out, it is indeed

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

Upvotes: 17

Related Questions