Here we will learn ng-switch directive in angularjs with the example, use of ng-switch in angularjs and how to use ng-switch with multiple when conditions with example.
In angularjs, ng-switch
directive will behave same as a switch-case statement in general programming scenario. In angularjs, ng-switch
is useful to conditionally swap between the HTML DOM elements based on the data model written in the expression.
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>
</div>
We will see how to use ng-switch directive in angularjs application with simple example.
Following is the example of using ng-switch
directive in angularjs applications.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs ng-switch Directive Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("AngularswitchApp", []);
app.controller("ngswitchctrl", function ($scope) {
$scope.items = ['one', 'two', 'three', 'four'];
$scope.selectval = "one";
});
</script>
</head>
<body ng-app="AngularswitchApp">
<div ng-controller="ngswitchctrl">
Select Item: <select ng-model="selectval" ng-options="item for item in items">
</select>
<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>
</div>
</div>
</body>
</html>
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.
Following is the result of using ng-switch directive in angularjs applications.
This is how we can use ng-switch
directive in angularjs application to check multiple conditions based on our requirements.