Angularjs ng-switch directive is used to conditionally swap DOM structure on your template based on a scope expression.
ng-switch usage
<ANY ng-switch="expression"> <ANY ng-switch-when="matchValue1">...</ANY> <ANY ng-switch-when="matchValue2">...</ANY> <ANY ng-switch-default>...</ANY> </ANY>
Example – horizontal tabs using ng-switch
<style>
.tabmenu {margin-top: 20px; border-bottom: 1px solid;}
.tabmenu li.active {border: 1px solid; border-bottom: 1px solid #fff;}
.tabmenu li {display:inline; cursor: pointer; padding: 0 10px;}
</style>
<div ng-app="myApp" ng-controller='MyCtrl'>
<ul class="tabmenu">
<li ng-class="{'active': tabName=='tab1'}" ng-click="tabName='tab1'">Tab1</li>
<li ng-class="{'active': tabName=='tab2'}" ng-click="tabName='tab2'">Tab2</li>
</ul>
<div ng-switch="tabName">
<div ng-switch-when="tab1"><p>tab1 content</p></div>
<div ng-switch-when="tab2"><p>tab2 content</p></div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {
$scope.tabName = "tab1";
});
</script>Few points to note:
- We can use ng-include to include a template in ng-switch-when content section.
- Here ng-class is being used to have a class name if a specific condition is met.
ng-class="{'active': tabName=='tab1'}"It can also be used multiple times in same element.