3

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.

Jordash
  • 2,926
  • 8
  • 38
  • 77

2 Answers2

6

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>
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

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.

Community
  • 1
  • 1
Dylan Watt
  • 3,357
  • 12
  • 16