<div ng-show="2 + 2 == 5">2 + 2 isn't 5, don't show</div><div ng-show="2 + 2 == 4">2 + 2 is 4, do show</div>ng-if指令可以根據表達式的值在DOM中生成或移除一個元素。如果賦值給ng-if的表達式的值是false,那對應的元素將會從DOM中移除,否則生成一個新的元素插入DOM中。ng-if同no-show和ng-hide指令最本質的區別是,它不是通過CSS顯示或隱藏DOM節點,而是刪除或者新增結點。[Javascript] view plain copy print?<div ng-if=“2+2===5”> Won’t see this DOM node, not even in the source code </div> <div ng-if=“2+2===4”> Hi, I do exist </div>
<div ng-if="2+2===5">Won't see this DOM node, not even in the source code</div><div ng-if="2+2===4">Hi, I do exist</div>ng-if重新創建元素時用的是它們編譯后的狀態。如果ng-if內部的代碼加載之后被jQuery修改過(例如用.addClass),那么當ng-if的表達式值為false時,這個DOM元素會被移除,表達式再次成為true時這個元素及其內部的子元素會被重新插入DOM,此時這些元素的狀態會是它們的原始狀態,而不是它們上次被移除時的狀態。也就是說無論用jQuery的.addClass添加了什么類都不會存在了。而ng-show和ng-hide則可以保留dom元素上次修改后的狀態。當一個元素被ng-if從DOM中移除,同它關聯的作用域也會被銷毀。而且當它重新加入DOM中時,會通過原型繼承從它的父作用域生成一個新的作用域。也就是說ng-if會新建作用域,而ng-show和ng-hide則不會。[html] view plain copy print?<html ng-app> <head> <script src=“angular-1.2.25.js”></script> <script> function myController(scope) </span></li><li class=""><span> { </span></li><li class="alt"><span> scope.keyworld = “”; } </script> </head> <body ng-controller=“myController”> <input type=“text” ng-model=“keyworld”> <input type=“button” value=“clear” ng-click=“keyworld=”” ng-show=“keyworld !=” ”> </body>
<html ng-app><head> <script src="angular-1.2.25.js"></script> <script> function myController($scope) { $scope.keyworld = ""; } </script></head><body ng-controller="myController"> <input type="text" ng-model="keyworld"> <input type="button" value="clear" ng-click="keyworld=''" ng-show="keyworld !='' "></body>
新聞熱點
疑難解答