<!DOCTYPE html> <html> <head> <script src="angular.js"></script> </head> <body ng-app> <label>Type the number you want to show (1 to 5): <input type="text" ng-model="showNumber" /></label><br /> <div ng-switch="showNumber"> <div ng-switch-when="1" style="width: 50px; background-color: red; text-align: center;">1</div> <div ng-switch-when="2" style="width: 50px; background-color: green; text-align: center;">2</div> <div ng-switch-when="3" style="width: 50px; background-color: yellow; text-align: center;">3</div> <div ng-switch-when="4" style="width: 50px; background-color: fuchsia; text-align: center;">4</div> <div ng-switch-when="5" style="width: 50px; background-color: orange; text-align: center;">5</div> <div ng-switch-default style="width: 50px; background-color: lightgray; text-align: center;">None</div> </div> </body> </html>



The ng-switch directive allows us to conditionally insert or remove an element in the DOM.

There are 3 directives involved in the use of ng-switch:

  • ng-switch
  • ng-switch-when
  • ng-switch-default

If we take a look at the example everything will be clear. You add the ng-switch directive to a container element (a div in this case) and set the expression that acts as a selection condition (in this case we use the showNumber model variable). Then you add a ng-switch-when directive to every child element that you want to include or remove from the DOM specifying the condition that, if matched, makes the element included in the DOM. In case no condition is true among the ng-switch-when alternatives, the element included in the DOM will be the one with the ng-switch-default directive.

The ng-switch directive creates a new scope.