AngularJS – ng-switch 指令


AngularJS 中的 ngSwitch 指令有條件地交換基於範圍表示式的模板上的 DOM 結構。此指令可用於基於 switch 情況顯示或隱藏元素。

僅當 ngSwitch 指令內的表示式的結果為 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>

示例 − ngSwitch 指令

在您的 Angular 專案目錄中建立檔案 "ngSwitch.html" 並複製貼上以下程式碼片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngSwitch Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">             </script>
   </head>

   <body ng-app style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngSwitch Directive
      </h2>

      <div>
         <form>
            <label>
               <input type="radio" value="search" ng-model="switch.Data" />
               FrontEnd Frameworks
            </label>
            <label>
               <input type="radio" value="sort" ng-model="switch.Data" />
               Backend Technologies
            </label>
         </form>

         <div ng-switch="switch.Data" id="wrapper">
            <div ng-switch-when="search">
               <h2>FrontEnd Frameworks</h2>
               <ul>
                  <li>Angular JS</li>
                  <li>React JS</li>
                  <li>Vue JS</li>
               </ul>
            </div>
            <div ng-switch-when="sort">
               <h2>Backend Technologies</h2>
               <ul>
                  <li>C</li>
                  <li>C++</li>
                  <li>Java</li>
               </ul>
</div>
</div>
</div>
</body>
</html>

輸出

要執行以上程式碼,只需轉到您的檔案並像執行普通 HTML 檔案一樣執行它即可。您將在瀏覽器視窗中看到以下輸出。

示例 2

在您的 Angular 專案目錄中建立檔案 "ngSwitch.html" 並複製貼上以下程式碼片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngSwitch Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
      </script>
   </head>

   <body ng-app style="text-align: center;">

   <h1 style="color:green">
      Welcome to Tutorials Point
   </h1>
      <h2>
         AngularJS | ngSwitch Directive
   </h2>

   <div>
      <div class="col-md-3">
         Type value(true/false):
         <input ng-model="value" type="value" />
      </div><br>

      <div ng-switch="value" class="col-md-3">
         <div ng-switch-when="true" class="btn btn-danger">
            You entered <b>{{value}}</b>
         </div>

         <div ng-switch-when="false" class="btn btn-primary">
            You entered <b>{{value}}</b>
         </div>

         <div ng-switch-default class="well">
            This is the default section.
         </div>
      </div>
   </div>

</body>
</html>

輸出

要執行以上程式碼,只需轉到您的檔案並像執行普通 HTML 檔案一樣執行它即可。您將在瀏覽器視窗中看到以下輸出。

更新於: 2021-10-08

509 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告
© . All rights reserved.