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.

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This is good. You may need to use ng-cloak to prevent "not set" from flickering on the screen on load.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.