Daft
Daft

Reputation: 10964

Conditionally add string to HTML with Angular expression

I have the following :

<div>{{animalType}}</div>

which evaluates to dog.

Can I conditionally add an sif animalTypeevaluates to anything other than dog?

Something like this : which doesn't work

<div>{{animalType}} {{'s' : !animalType == 'dog'}}</div> 

So I would getcats

Upvotes: 0

Views: 1959

Answers (4)

ukn
ukn

Reputation: 1793

You could also use ng-if

<div>{{animalType}}<div ng-if="animalType !== 'dog'">s</div></div>

Upvotes: 0

Max Yari
Max Yari

Reputation: 3697

Not tested, but try this simple snippet:

<div>{{animalType === "dog" ? animalType : "s"}}</div> 

By the way, if you want to switch only between two values, from my point of view, logically appealing would be something like that:

<div>{{isDog ? "dog" : "s"}}</div>

$scope.isDog = true/false

Upvotes: 0

Tushar
Tushar

Reputation: 87203

Use ternary operator in expression as follow:

<div>{{animalType}}{{animalType != 'dog' ? 's' : '' }}</div> 

Upvotes: 3

Stu
Stu

Reputation: 2446

Alternatively

<div>{{animalType}}<span ng-show="animalType!='dog'">s</span></div> 

Upvotes: 1

Related Questions