15

I'm using Angular and I want to check when a string is empty using ng-switch. The following code doesn't seem to be working for me.

<div ng-switch on="foo">
    <span ng-switch-when="">This string is empty</span>
    <span ng-switch-default>This string is not empty</span>
</div>

Any help with this would be appreciated.

1

3 Answers 3

21
<div ng-switch on="foo || 'null'">
    <span ng-switch-when="null">This string is empty</span>
    <span ng-switch-default>This string is not empty</span>
</div>
2
  • thats more helpful
    – manojadams
    Sep 14, 2017 at 16:02
  • Instead of 'null' you can write '' and then the ng-switch-when works as it was before. So you can use <div ng-switch="foo || ''" and then <span ng-switch-when="">...</span>
    – DWilches
    Oct 23, 2018 at 21:00
10

You will need to include the empty string in your controller:

function Ctrl($scope) {
  $scope.items = ['', 'other'];
  $scope.selection = $scope.items[0];
}

For additional reference, see the API: http://docs.angularjs.org/api/ng.directive:ngSwitch

Also, here's a working version of your code: http://jsfiddle.net/upPgU/

0
4

Definite dupe of Angular.js ng-switch ---testing if value is empty or undefined.

The accepted answer isn't ideal there either. In my oh so humble opinion the most elegant and clear solution has the least upvotes over there.

<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>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.