How to use Switch Case in AngularJS?

As an efficient programmer you must know the benefits of using switch case in place of if & else. Modern Programming languages compiles switch case more faster than if & else. During application development using switch case we can achieve better performance for conditional checking. It’s no matter if you are using if & else for 4 to 5 conditional checking. But in-case of we are going to check more then 5 to 10 conditional checking I can suggest you to use switch case.

In the below example I am showing how to use Switch Case in AngularJS. Look at the Code below. Here inside the controller I declared options to the Scope. Options array contains six items. In html body I have a dropdownlist which shows me the list of values from the options array. Depending upon the selected value from dropdownlist I am showing a div with appropriate message. In the primary div of switch cases messages I am using ng-switch on=”selection” to instruct on which values switch case will occur. Here “selection” is my ng-model. Which is declared in my select control. To check each case from options array I am using ng-switch-when & for default value like ‘Others’ from options array I am using ng-switch-default to show the default massage.

To run the below example copy the codes to a Notepad file. Save it as a html file & run it with internet Connectivity.

Switch Case in AngularJS Example

<!DOCTYPE html>
<html>
<head>
<title>How to use Switch Case in AngularJS?</title>
<!--AngularJS CDN Link-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript">
(function(angular) {
angular.module('modSwitch', [])
.controller('ControllerSwitch', ['$scope', function($scope) {
$scope.options = ['Blog', 'Business', 'Fashion', 'Career', 'Education', 'Others'];
$scope.selection = $scope.options[0];
}]);
})(window.angular);
</script>
</head>
<body ng-app="modSwitch">
<div ng-controller="ControllerSwitch">
<select ng-model="selection" ng-options="item for item in options">
</select>
<hr/>
<div ng-switch on="selection">
<div ng-switch-when="Blog">Blog is a Business.</div>
<div ng-switch-when="Business">Business is a Busy Game.</div>
<div ng-switch-when="Fashion">Fashion updates Everyday.</div>
<div ng-switch-when="Career">Career is Like a Ladder.</div>
<div ng-switch-when="Education">Education Never Ends.</div>
<div ng-switch-default>This is the Default value for Switch Case.</div>
</div>
</div>
</body>
</html>