Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular is possible to use ngSwitch on numeric range?

Tags:

angularjs

I would like to use ngSwitch based on numeric value range.

I would like to show three different text based on ngSwitch change. However I cannot get this work when I try to set a value range in ng-switch-when. Is this possible or should I use ngIf instead of ngSwitch?

http://jsbin.com/eWIQoJE/1/edit

like image 609
Tropicalista Avatar asked Dec 15 '13 13:12

Tropicalista


People also ask

What is the use of ngSwitch in angular?

AngularJS ng-switch Directive 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.

What is the difference between ngIf and ngSwitch?

The important difference between the ngIf solution is that through NgSwitch we evaluate the expression only once and then select the element to display depending on the result. Using ngIf we can conditionally add or remove an element from the DOM.

What type of directive is ngSwitch?

The ngSwitch is an Angular structural directive, which allows us to add or remove DOM elements. It works in conjunction with ngSwitchcase , & ngSwitchDefault directives. It is similar to the switch statement of JavaScript.


2 Answers

It's not possible.

The ngSwitch directive checks if the value in ngSwitchWhen is equal to the one in ngSwitch. Instead, you can use ngShow or ngIf as you have proposed:

 <div ng-if="test === 0">Is zero</div>
 <div ng-if="test > 10">Is greater than 10</div>
 <div ng-if="!(test === 0 || test > 10)">Default</div>

JSBin

like image 166
Blackhole Avatar answered Sep 28 '22 02:09

Blackhole


It is possible, but you need to declare a helper function in your scope

In your controller:

$scope.switchHelper = function(value) {
  if (value === 0)
    return 0;
  if (value > 10)
    return 1;
  if (!(value === 0 || test))
    return 3;
};

An in HTML:

<div ng-switch="switchHelper(test)">
     <div ng-switch-when="0">Is zero</div>
     <div ng-switch-when="1">Is greater than 10</div>
     <div ng-switch-when="3">Default</div>
</div>

As JSBin.

like image 24
TheHippo Avatar answered Sep 28 '22 03:09

TheHippo