您的位置:首页 > Web前端 > AngularJS

ng-if、ng-show和ng-hide指令的区别

2017-02-09 17:02 681 查看
angularJS中的ng-show、ng-hide、ng-if指令都可以用来控制dom元素的显示或隐藏。ng-show和ng-hide根据所给表达式的值来显示或隐藏HTML元素。当赋值给ng-show指令的值为false时元素会被隐藏,值为true时元素会显示。ng-hide功能类似,使用方式相反。元素的显示或隐藏是通过改变CSS的display属性值来实现的。
[javascript] view plain copy print?<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-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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angularjs 前端