angularJS中的ng-show、ng-hide、ng-if指令都可以用来控制dom元素的显示或隐藏。ng-show和ng-hide根据所给表达式的值来显示或隐藏HTML元素。当赋值给ng-show指令的值为false时元素会被隐藏,值为true时元素会显示。ng-hide功能类似,使用方式相反。元素的显示或隐藏是通过改变CSS的display属性值来实现的。
<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节点,而是删除或者新增结点。
<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>
<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>
这段代码默认情况下clear按钮不显示;当在text中输入内容时,clear按钮会显示;点击clear按钮时,会清空text中的内容,同时隐藏clear按钮。可以看到使用ng-show和ng-hide功能完全正常。如果将ng-show改成ng-if,点击clear按钮的时候,不能清空text中的内容,也不能隐藏clear按钮。这是因为ng-if会新建或者销毁作用域,很类似于javascript的原型继承。
原文:http://www.cnblogs.com/lodingzone/p/4950563.html