0

I need to write an angular ng-switch with 4 conditions.

Some other answers here on SO suggest using ng-if instead of ng-switch.

And so I tried with the ng-if, but I don't really think this is the best way and I'll explain why:

Basically I need to display 3 different icons, depending on some variables I've got in my scope.

The code in my template is the following:

<div class="buttons">
   <div ng-if="test.mMode==4 && test.kit==4 && test.react.on==true && test.act==1">
      <i class="icon ion-man"></i>
   </div>

   <div ng-if="test.mMode==4 && test.kit==4 && test.react.on==false && test.act==1">
      <i class="icon ion-man"></i>
   </div>

   <div ng-if="zone.iActivity==1">
      <i class="icon ion-man"></i>
   </div>
</div>

Now, this, to me, looks really really messy. And Also, it doesn't work as expected, as it iterates trough all of the if statements printing all the true.

is it possible to do something like the follow instead?

<div class="buttons" ng-switch="test.act && test.Mode && test.kit && test.react.on">
   <div ng-switch-when="1 && 4 && 4 && true">
      <i class="icon ion-man"></i>
   </div>

   <div ng-switch-when="1 && 4 && 4 && false">
      <i class="icon ion-man"></i>
   </div>

   <div ng-switch-when="1"> //I need only the first condition to be true, I don't need the others.
      <i class="icon ion-man"></i>
   </div>
</div>

Or, do you have any other suggestions on how to properly handle this type of templating?

Hope the question is clear enough.

Thanks for any help

Nick
  • 13,493
  • 8
  • 51
  • 98
  • 1
    you probably should handle this in your controller instead of the view and add ng-show/ng-hide to the div's edit: [check this answer](http://stackoverflow.com/questions/31987314/showing-or-hiding-elements-based-on-variables-in-controller-ionic) – SeRu May 19 '16 at 11:49
  • Yeah I actually though about it, I was just wonder if this was possible trough the template or not. If not, I'll handle this in the controller instead – Nick May 19 '16 at 11:50
  • Maybe [this example](http://jsfiddle.net/nhLxad6t/) helps for understanding the use of ng-show/ng-hide – SeRu May 19 '16 at 12:19

1 Answers1

1

A little bit dirty solution would be to use array and toString() method.

<ng-switch on="[Ex1.x, Ex1.y].toString()">
    <div ng-switch-when="0,true">
      0,true -- jaj
    </div>
    <div ng-switch-when="1,true">
      1,true -- jaj
    </div>
    <div ng-switch-when="2,false">
      2,false -- jaj
    </div>
    <div ng-switch-default>
     default... booo
    </div>
  </ng-switch>

Fiddle: https://jsfiddle.net/r88dhr0w/

sielakos
  • 2,406
  • 11
  • 13