Angular.js ng-switch —testing if value is empty or undefined

All we need is an easy explanation of the problem, so here it is.

In Angular.js templating, I need to test if a value is undefined or empty…. I am not sure how to do this since ng-switch-when tests for expressions in strings. I needed to use ng-switch because it’s a if else condition. Any ideas?

<div ng-switch="vipLabel">
  <div ng-switch-when="vipLabel.toString()">
    <h1>Getting infomration...one sec</h1>
  </div>
    <div ng-switch-default>
      <h3>Do you wish to unbind {{node.label}} from {{ vipLabel }}?</h3>
    </div>
</div>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

ng-switch allows expressions, you can use placeholder, as such:

<div ng-switch="selection || '_undefined_'" >      
      <span ng-switch-when="_undefined_">I am set to zero or undefined?!</span>      
      <span ng-switch-default>This string is not empty</span>
</div>

For more info: ng-switch on empty string

You usually do it within controller(see answer#1 in linked thread).

Method 2

<div ng-switch="!!selection">
   <div ng-switch-when="false">Empty, Null or undefined</div>
   <div ng-switch-when="true">The string is not empty</div>
</div>

Method 3

Following solution would also work (using angular 1.3.10):

<div ng-switch="selection">
    <div ng-switch-default>The string is not empty!</div>
    <div ng-switch-when="undefined">The string is empty!</div>
</div>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply