AngularJS ng-switch 指令

定義和用法

ng-switch 指令允許您根據表達式隱藏/顯示 HTML 元素。

如果子元素通過 ng-switch-when 指令獲得匹配項,則會顯示帶有 ng-switch-when 指令的子元素,否則將刪除該元素及其子元素。

您還可以使用 ng-switch-default 指令定義默認部分,以便在其他部分均不匹配時顯示該部分。

實例

只有當它匹配某個特定值時,才顯示一部分 HTML:

<div ng-switch="myVar">
  <div ng-switch-when="dogs">
    <h1>Dogs</h1>
    <p>Welcome to a world of dogs.</p>
  </div>
  <div ng-switch-when="tuts">
    <h1>Tutorials</h1>
    <p>Learn from examples.</p>
  </div>
  <div ng-switch-when="cars">
    <h1>Cars</h1>
    <p>Read about cars.</p>
  </div>
  <div ng-switch-default>
    <h1>Switch</h1>
    <p>Select topic from the dropdown, to switch the content of this DIV.</p>
  </div>
</div>

親自試一試

語法

<element ng-switch="expression">
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-default></element>
</element>

所有 HTML 元素都支持。

參數

參數 描述
expression 表達式,將刪除沒有匹配項的元素,并顯示有匹配項的元素。