pTutorial

New way to learn Programming

AngularJS ng-switch Example

The ng-switch directive is basically used to insert conditional element like ng-if.

There are 3 directives involved in the use of ng-switch:

  • ng-switch
  • ng-switch-when
  • ng-switch-default

ng-switch example

<!DOCTYPE html>
<html>
<head>
 <script src="http://ajax.googleapis.com/ajax/
 libs/angularjs/1.3.14/angular.min.js"></script>
<style>
.uk{
	font-size:36px;
	text-align:center;
	margin:10px;
	border-radius:25px;
}
.uk1{
	font-size:36px;
	text-align:center;
	margin:10px;
}

.uk3{
	font-size:36px;
	text-align:center;
	margin:10px;
}

.uk2{
	font-size:36px;
	text-align:center;
	margin:10px;
	border-radius:100px;
}
</style>

</head>

<body ng-app>
<h3>Enter a to d and see the result</h3>
 <input type="text" ng-model="temp"/><br/>
  <div ng-switch="temp">
    <div style="background:#00F;" ng-switch-when="a" 
	class="uk">You pressed a</div>
    <div style="background:#F00;" ng-switch-when="b" 
	class="uk1">You pressed b</div>
    <div style="background:#0C0;" ng-switch-when="c" 
	class="uk3">You pressed c</div>
    <div style="background:#C33;" ng-switch-when="d" 
	class="uk2">You pressed d</div>
  
      <div style="background:#9FC;" ng-switch-default 
	  class="uk2">You have not pressed anything</div>
  </div>
</body>
</html

Download


Explanation

The ng-switch is used as a container and bind with input field expression then the input field works as condition selector.

The ng-switch-when is use for child elements that you want to add from the DOM specifying the condition that, if the condition matched, element is added otherwise ng-switch-default element added.

See the following example to understand about the ng-switch directive.

See Also


QUOTES OF THE DAY

Knowledge itself is a power.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER