AngularJS – ng-switch 指令

AngularJS 中的ngSwitch指令根据范围表达式有条件地交换模板上的 DOM 结构。该指令可用于根据 switch case 显示或隐藏元素。

仅当 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 xx_src="https://cdn.staticfile.org/angularjs/1.6.9/angular.min.js">             </script>
   </head>

   <body ng-app style="text-align: center;">
      <h1 style="color: green;">
         Welcome to nhooo.com
      </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 xx_src="https://cdn.staticfile.org/angularjs/1.6.9/angular.min.js">
      </script>
   </head>

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

   <h1 style="color:green">
      Welcome to nhooo.com
   </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 文件运行即可。您将在浏览器窗口中看到以下输出。