Jordash
Jordash

Reputation: 3103

Set HTML as default value of undefined variable in Angular JS

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.

Upvotes: 3

Views: 718

Answers (2)

Dylan Watt
Dylan Watt

Reputation: 3387

So if you really, really want to inject HTML, look at this question: With ng-bind-html-unsafe removed, how do I inject HTML?

But if you just want to show an error if it's not defined:

{{salesperson}}<span ng-if="!salesperson" class="error ng-cloak">- Not Set -</span>'

It will only show the span if salesperson is undefined. Make sure to define your ng-cloak css as well to prevent any flickering.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691775

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>

Upvotes: 6

Related Questions