ng-if与ng-show、ng-hide指令的区别和注意事项

        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>

        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 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的原型继承。

        StackOverflow上这篇文章,也有人提问ng-if和ng-show的差别。这里直接附上结论:
        1.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.
        2.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.
        3.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.

 

文章来源:http://blog.csdn.net/aitangyong/article/details/44701769

你可能感兴趣的:(JavaScript,AngularJS)