AngularJS ng-switch Directive with Example

Here we will learn ng-switch directive in angularjs with example, use of ng-switch in angularjs and how to use ng-switch with multiple when conditions with example.

AngularJS ng-switch Directive

In angularjs, ng-switch directive will behave similar to the switch case in general programming scenario. In angularjs, ng-switch is used to conditionally swap between the HTML DOM elements based on the data model wrote in the expression.

AngularJS ng-switch Directive Syntax

Following is the syntax of using ng-switch directive in angularjs applications.


<div ng-switch="expression">

<div ng-switch-when="matchval1">..your code..</div>

<div ng-switch-when="matchval2">..your code..</div>

<div ng-switch-default>..your code..</ANY>


We will see how to use ng-switch directive in angularjs application with simple example.

AngularJS ng-switch Directive Example

Following is the example of using ng-switch directive in angularjs applications.


Live Preview

<!DOCTYPE html>

<html xmlns="">



AngularJs ng-switch Directive Example


<script src=""></script>


var app = angular.module("AngularswitchApp", []);

app.controller("ngswitchctrl", function ($scope) {

$scope.items = ['one', 'two', 'three', 'four'];

$scope.selectval = "one";




<body ng-app="AngularswitchApp">

<div ng-controller="ngswitchctrl">

Select Item: <select ng-model="selectval" ng-options="item for item in items">


<div ng-switch ="selectval">

<div ng-switch-when="one"><b>DIV1</b>: You Selected value one</div>

<div ng-switch-when="two"><b>DIV2</b>: You Selected value two</div>

<div ng-switch-when="three"><b>DIV3</b>: You Selected value three</div>

<div ng-switch-default>You are in default switch case.</div>





In above example if you observe we defined a div elements with an ng-switch attribute and on attribute. The on attribute tell on which data of the model the switch will be applied on. Inside the switch element we have four <div> elements.


The first three elements have the attribute ng-switch-when and the last div element have the attribute ng-switch-default. They act same as the switch case.


If the related data model contains the value matched to the given value then the respective div will be shown else the default div will be shown. Now we will run the application and will see how result will be.

Output of AngularJS ng-switch Example

Following is the result of using ng-switch directive in angularjs applications.


Angularjs ng-switch directive example output or result


This is how we can use ng-switch directive in angularjs application to check multiple conditions based on our requirements.