AngularJs ngIf、ngSwitch、ngHide/ngShow
在組合這些ng指令寫到一篇文章里的時候,基本是有規(guī)則的,本獸會將功能相似相近的一類整合到一篇文章,方便理解和記憶。
這篇的三個指令也都是對DOM元素的操作,頁面上顯示/隱藏的判斷,添加/移除的判斷。
ngIf
ngIf指令會根據(jù)指定的表達式返回的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的顯示/隱藏效果。但是如果你打開瀏覽器開發(fā)工具去審查元素,會發(fā)現(xiàn)這個div是被移除和添加的,只留下一個注釋“<!-- ngIf: show -->”在div所在的地方。這個需要和下面的ngShow/ngHide做個區(qū)分。也就是說這個指令對DOM的操作是移除出/添加進DOM樹了。
ngSwitch
ngSwitch指令可以根據(jù)表達式的結果在模板上按條件切換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根據(jù)表達式的成立與否添加對應的內容到寫好的HTML位置,而這個位置當表達式為false時也是個注釋就像:“<!-- ngSwitchWhen: tpl-two -->”。這是第二個模板綁定的位置,當表達式滿足第二個模板的條件,那么這里就會被第二個模板的HTML代替并顯示到頁面。
ngHide/ngShow
NgHide/ngShow指令顯示或隱藏指定的THML元素。元素的顯示隱藏是根據(jù)元素上ng-hide的css樣式添加刪除實現(xiàn)的。
格式: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 {/* this is just another form of hiding an element */display: block!important;position: absolute;top: -9999px;left: -9999px;}轉載于:https://www.cnblogs.com/ys-ys/p/4965139.html
總結
以上是生活随笔為你收集整理的AngularJs ngIf、ngSwitch、ngHide/ngShow的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python画五子棋棋盘_python
- 下一篇: Android自己的自动化测试Monke