AngularJS – implement tabs using ng-switch

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>

Example – horizontal tabs using ng-switch

.tabmenu {margin-top: 20px; border-bottom: 1px solid;}
.tabmenu {border: 1px solid; border-bottom: 1px solid #fff;}
.tabmenu li {display:inline; cursor: pointer; padding: 0 10px;}

<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>

  <div ng-switch="tabName">
    <div ng-switch-when="tab1"><p>tab1 content</p></div>
    <div ng-switch-when="tab2"><p>tab2 content</p></div>

<script src="//"></script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {
  $scope.tabName = "tab1";

Few points to note:

  1. We can use ng-include to include a template in ng-switch-when content section.
  2. 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.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments