Introducing ng-switch

The ng-switch directive is conditional switch structure type that is used directly in the template. It can display a particular element on the value of the expression it evaluates.

In this example, if the variable contains someVar “hey”, the first div will be displayed, if it contains “hi”, the second div will be displayed, and if it contains no “hey” or “hi” will be the third div displayed:

<div ng-switch="someVar">
    <div ng-switch-when="hey">
    </div>
    <div ng-switch-when="hi">
    </div>
    <div ng-switch-default>
    </div>
</div>

Unlike ng-show and hide that just display or hide an item in the eyes of the user, ng-switch actually removes DOM elements not used (but they are well kept in memory). If one element contains a video that starts on loading of the page, it will be played only when the item is displayed.

Why use ng-switch?

  • Ng-Switch is used to conditionally swap DOM structure on your template based on a scope expression
  • Manage different display modes of your webapp
  • In general, present a different visual to your context according to the values passed

Ng-switch Demo

Click here for the source code

mss_index.js

<!doctype html>
<html  ng-app="mssApp">
    <head>
    <meta charset="UTF-8">
    <title>The ng-switch directive</title>
    <link rel="stylesheet" href="mss_style.css">
    </head>
<body>

<div ng-controller="MainCtrl">

    <!-- Choice Status -->
    <form >
    <label><input type="radio" value="admin" ng-model="FrontEndUsers.status" >
Click For Administrator</label>
    <label><input type="radio" value="contributor" ng-model="FrontEndUsers.status" >Click For Contributor</label>
    <label><input type="radio" value="visitor" ng-model="FrontEndUsers.status" >Click For Visitor</label>
    </form>

    <hr>

    <!-- See the section that corresponds to the status -->
    <div  ng-switch="FrontEndUsers.status" id="wrapper">
    <div ng-switch-when="admin">
    <h2> Admin Section</h2>
    </div>
    <div ng-switch-when="contributor">
    <h2>Contributor Section </h2>
    </div>
    <div ng-switch-default>
    <h2> Visitor Section</h2>
    </div>
    </div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<script src="mss_app.js"></script>
</body>
</html>


mss_app.js

var app = angular.module('mssApp', []);

app.controller( 'MainCtrl' , function( $scope ) {

    $scope.FrontEndUsers = {

    status :'visitor'
    };
});

Code Explanation

MainCtrl The controller contains a user object.

3 radio buttons have the ng-model attribute with value user.status, which means that when you click on one of them, user.status is updated accordingly.

ng-switch user.status evaluates and displays one of three div depending on the value:

  • If the value is “admin”, the first div is displayed
  • If the value is “contributor”, the second div is displayed
  • If the value is not “admin” or “contributor”, the third div is displayed