Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 403
que1326 Avatar asked Mar 30 '16 11:03

que1326


People also ask

Can you change the id of an element in JavaScript?

Approach 2: We can use the id property inside the element to change the ID using JavaScript.

What is the id attribute used for in HTML?

The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).


2 Answers

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>
like image 70
fikkatra Avatar answered Sep 29 '22 06:09

fikkatra


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

id="{{expression ? 'this-one': 'that-one'}}"
like image 39
a_lovelace Avatar answered Sep 29 '22 05:09

a_lovelace