ng-switch directive in angular



Today we will see how to use ng-switch directive in angularjs. We can use ng-show to show or hide html elements but when we need to check multiple conditions ng-switch suits best. Ng-switch is analogous to switch condition in our programming languages.

First I will take a drop down list and add some values to it. I will catch the selected value using ng-model directive. Later I will be passing this selected value to ng-switch directive as input.














<select ng-change="onChange()" ng-model="selectedVal">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
    </select>
  

We have our dropdownlist in place, Let's go ahead and try to use ng-switch to change the view based on the selection of the dropdownlist value.
As mentioned earlier the ng-switch is similar to switch statement in javascript or C, we can have a default case in ng-switch directive which is demonstrated below. If none of the conditions are met ng-switch-default will be rendered.

<div ng-switch="" on="selectedVal">
<div ng-switch-when="1">
<h1>
This is First Div</h1>
</div>
<div ng-switch-when="2">
<h1>
This is Second Div</h1>
</div>
<div ng-switch-when="3">
<h1>
This is Third Div</h1>
</div>
<div ng-switch-default="">
<h1>
This is default div</h1>
</div>
</div>

The working demo can be found here

Comments

Popular Posts