How to do if/else logic in Anglular using ng-switch

Although Angular has an ng-if, there is no direct concept of an ng-else, so you can easily end up writing some nasty conditional logic.

<div ng-if="!inputText">      
  <span>Enter a value!</span>      
</div>
<div ng-if="inputText == 'Boo'">      
  <span>Boo who?"</span>      
</div>
<div ng-if="inputText && inputText != 'Boo'">      
  <span>You entered "{{inputText}}"</span>      
</div>

Ugly! A better way is with ng-switch

It turns out that ng-switch is a better approach, but you do have to watch out for a small gotcha.

At first guess, you'd think this would do nicely:

<div ng-switch="inputText" >
  <span ng-switch-when="">Enter a value!</span>
  <span ng-switch-when="Boo">Boo who?</span>
  <span ng-switch-default>You entered "{{inputText}}"</span>
</div>

Did you notice that the "Enter a value!" text didn't initially show?

We didn't handle the undefined, null or empty string case. Everything in the ng-switch-when attribute needs to be a value, so we need to come up with something to represent undefined, null, etc.

By changing the ng-switch statement to use logical OR's, we can massage inputText into a useful value to be matched in an ng-switch-when.

<div ng-switch="inputText || '_undefined_'" >
  <span ng-switch-when="_undefined_">Enter a value!</span>
  <span ng-switch-when="Boo">Boo who?</span>
  <span ng-switch-default>You entered "{{inputText}}"</span>
</div>

Much better! Our code is now cleaner, a lot more maintainable, and of course readable.