标签:ng-if和ng-show的差别 使用ng-if时ng-click无效 小心ng-if的使用
<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>
<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的原型继承。可以参考这2篇文章:
ng-if
will
remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if
evaluates
to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if
later
evaluates to true and displays the element. You will need to reattach the handler.ng-show/ng-hide
does
not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.ng-if
creates
a child scope while ng-show/ng-hide
does
not
Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if
compared
to ng-show/ng-hide
.
In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.
(十四)ng-if与ng-show、ng-hide指令的区别和注意事项
标签:ng-if和ng-show的差别 使用ng-if时ng-click无效 小心ng-if的使用
原文地址:http://blog.csdn.net/aitangyong/article/details/44701769