Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-switch on empty string

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.

like image 629
Timothy Owen Avatar asked Sep 15 '12 03:09

Timothy Owen


People also ask

What is* NgSwitchCase?

NgSwitchCaselinkProvides a switch case expression to match against an enclosing ngSwitch expression. When the expressions match, the given NgSwitchCase template is rendered. If multiple match expressions match the switch expression value, all of them are displayed.

What is the use of NG-switch?

The ng-switch directive lets you hide/show HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match, otherwise the element, and its children will be removed.

Can we use switch case in angular?

AngularJS is built on top of JavaScript and it has no different syntax for switch case than JavaScript(As long as you are using it in script).

Which directive allows to conditionally Swap the contents of a section based on matched value?

The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression.


2 Answers

<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>
like image 118
Christina Avatar answered Sep 18 '22 14:09

Christina


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/

like image 31
Merbs Avatar answered Sep 22 '22 14:09

Merbs