AngularJS中的ng-switch指令用於指定在HTML DOM中顯示/隱藏子元素的條件。僅當ng-switch指令中的表達式返回true時,才會顯示HTML元素,否則它將被隱藏。所有HTML元素都支持它。
用法:
<element ng-switch="expression"> <element ng-switch-when="value"> Contents... </element> <element ng-switch-when="value"> Contents... </element> <element ng-switch-default> Contents... </element> </element>
範例1:本示例使用ng-switch指令切換元素。
<!DOCTYPE html>
<html>
<head>
<title>ng-switch Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
</head>
<body ng-app="" style="">
<h1 style="color:green;">GeeksforGeeks</h1>
<h2>ng-switch Directive</h2>
<div>
<form>
<label>
<input type="radio" value="search" ng-model="switch.Data">
Searching Algorithms
</label>
<label>
<input type="radio" value="sort" ng-model="switch.Data">
Sorting Algorithms
</label>
</form>
<div ng-switch="switch.Data" id="wrapper">
<div ng-switch-when="search">
<h2> Searching Algorithms</h2>
<ul>
<li>Binary Search
<li>Linear Search
</ul>
</div>
<div ng-switch-when="sort">
<h2>Sorting Algorithms</h2>
<ul>
<li>Merge Sort
<li>Quick Sort
</ul>
</div>
</div>
</div>
</body>
</html>
輸出:
- 之前單擊單選按鈕:
- 單擊搜索單選按鈕後:
- 單擊排序單選按鈕後:
範例2:本示例使用ng-switch指令顯示輸入的數字。
<!DOCTYPE html>
<html>
<head>
<title>ng-switch Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-app="" style="text-align:center;">
<h1 style="color:green;">GeeksforGeeks</h1>
<h2 style="">ng-switch Directive</h2>
<div>
<div class="col-md-3">
Type Number(1-2):
<input ng-model="number" type="number" />
</div><br>
<div ng-switch="number" class="col-md-3">
<div ng-switch-when="1" class="btn btn-danger">
You entered {{number}}
</div>
<div ng-switch-when="2" class="btn btn-primary">
You entered {{number}}
</div>
<div ng-switch-default class="well">
This is the default section.
</div>
</div>
</div>
</body>
</html>
輸出:
- 輸入文字之前:
- 輸入文字後:
相關用法
- AngularJS ng-if用法及代碼示例
- AngularJS ng-cut用法及代碼示例
- AngularJS ng-value用法及代碼示例
- AngularJS ng-src用法及代碼示例
- AngularJS ng-app用法及代碼示例
- AngularJS ng-csp用法及代碼示例
- AngularJS ng-jq用法及代碼示例
- AngularJS ng-required用法及代碼示例
- AngularJS ng-bind用法及代碼示例
- AngularJS ng-srcset用法及代碼示例
- AngularJS ng-paste用法及代碼示例
- AngularJS ng-submit用法及代碼示例
- AngularJS ng-style用法及代碼示例
- AngularJS ng-selected用法及代碼示例
注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | ng-switch Directive。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。