Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set HTML as default value of undefined variable in Angular JS

Tags:

angularjs

I have a variable that could be potentially unset like this

{{salesperson || 'not set'}}

I want to add a CSS class to the not set area like this

{{salesperson || '<span class="error">- Not Set -</span>'}}

When I tried that it throws syntax errors.

like image 441
Jordash Avatar asked Nov 22 '25 12:11

Jordash


1 Answers

HTML in expressions is escaped by angular, to avoid HTML/JS injections.

Use ng-class:

<span ng-class="{error: !salesperson}">{{salesperson || 'not set'}}</span>

Or simply ng-show/ng-hide:

<span ng-hide="salesperson" class="error">not set</span>
<span ng-show="salesperson">{{ salesperson }}</span>
like image 125
JB Nizet Avatar answered Nov 24 '25 07:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!