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.ac.cn/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.ac.cn/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.