AngularJs ngIf、ngSwitch、ngHide/ngShow


在組合這些ng指令寫到一篇文章里的時候,基本是有規則的,本獸會將功能相似相近的一類整合到一篇文章,方便理解和記憶。

這篇的三個指令也都是對DOM元素的操作,頁面上顯示/隱藏的判斷,添加/移除的判斷。

ngIf

ngIf指令會根據指定的表達式返回的boolean類型值對該元素做添加到/移除出Dom樹的操作。

格式:ng-if=“value”

value:表達式  返回結果為boolean類型。

使用代碼:

  <input type="button" value="show/hide" ng-click="show = !show;" />
  <div ng-if="show">Hello World</div>

這里做了個對Hello World 所在的div的顯示/隱藏效果。但是如果你打開瀏覽器開發工具去審查元素,會發現這個div是被移除和添加的,只留下一個注釋“<!-- ngIf: show -->”在div所在的地方。這個需要和下面的ngShow/ngHide做個區分。也就是說這個指令對DOM的操作是移除出/添加進DOM樹了。

ngSwitch

ngSwitch指令可以根據表達式的結果在模板上按條件切換DOM結構。元素內使用ngSwitch而沒使用ngSwitchWhen或者ngSwitchDefault指令的將會被保存在模板中。

格式:ng-switch  on=“expression” ng-switch-default  ng-switch-when=“value”

expression: 表達式,返回判斷的條件是否成立的boolean值。

value:設置的條件

使用代碼:

  <div ng-app="Demo" ng-controller="testCtrl as ctrl">
      <select ng-model="ctrl.tpl" ng-options="i for i in ctrl.select">
         <option value="0">請選擇模板</option>
      </select>
      <div ng-switch on="ctrl.tpl">
         <p ng-switch-default>tpl-one</p>
         <p ng-switch-when="tpl-two">tpl-two</p>
         <p ng-switch-when="tpl-three">tpl-three</p>
      </div>
  </div>
  (function () {
    angular.module("Demo", [])
    .controller("testCtrl", testCtrl);
    function testCtrl() {
        this.select = ["tpl-one", "tpl-two","tpl-three" ];
        this.tpl = this.select[0];
    };
  }());

ngSwitch根據表達式的成立與否添加對應的內容到寫好的HTML位置,而這個位置當表達式為false時也是個注釋就像:“<!-- ngSwitchWhen: tpl-two -->”。這是第二個模板綁定的位置,當表達式滿足第二個模板的條件,那么這里就會被第二個模板的HTML代替並顯示到頁面。

ngHide/ngShow

NgHide/ngShow指令顯示或隱藏指定的THML元素。元素的顯示隱藏是根據元素上ng-hide的css樣式添加刪除實現的。

格式:ng-hide=”value”   ng-show=”value”

value:表達式 結果為boolean類型。

使用代碼:

   <input type="button" value="show/hide" ng-click="show = !show;" />
   <div ng-show="show">Hello</div>
   <div ng-hide="show">World</div>

ngShow和ngHide相反。這里把ng-hide的css樣式寫在下面吧:

   .ng-hide {
     /&#42; this is just another form of hiding an element &#42;/
     display: block!important;
     position: absolute;
     top: -9999px;
     left: -9999px;
   }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM