[html]
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>ng-switch directive</title>
</head>
<body ng-app="spApp">
<h1>ng-switch directive</h1>
<div ng-controller="SPController">
<div ng-switch on="data.switch">
<div ng-switch-when="1">Shown when switch is 1</div>
<div ng-switch-when="2">Shown when switch is 2</div>
<div ng-switch-default>Shown when switch is anything else than 1 and 2</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="App.js"></script>
<script src="Controller.js"></script>
</body>
</html>
[/html]
[javascript]
myApp.controller("SPController", function($scope) {
$scope.data = {};
$scope.data.switch = 3;
});
[/javascript]
Above example contains a
div element with an
ng-switch attribute and on attribute. The
on attribute determines whether the data in the model should turn switch on.
Inside the
div element, there are three nested div elements. The first two nested div elements contain an
ng-switch-when attribute. The value of this attribute determines what value the model data referenced in the on attribute of the parent
div should have for the nested
div to be visible.
In this example, the first nested
div is visible when the value of
data.switch is
1 and the second nested
div is visible when the value of
data.switch is
2.
The third nested div has ng-switch-default attribute. If no other ng-switch-when directives are matched, then the div with the ng-switch-default attribute will be shown.
In the above example, the controller function sets
data.switch to
3 i.e. the nested div is shown along with
ng-switch-default attribute. Then, the two other settled
div components will be expelled from the DOM totally.
Output: