您的位置:首页 > 其它

ng-show和ng-if的区别

2017-06-06 11:27 253 查看
第一点区别是,
ng-if 在后面表达式为 true 的时候才创建这个 dom 节点,
ng-show 是初始时就创建了,用display:block 和 display:none 来控制显示和不显示。

第二点区别是,
ng-if 会(隐式地)产生新作用域,ng-switch 、 ng-include 等会动态创建一块界面的也是如此。
这样会导致,在 ng-if 中用基本变量绑定 ng-model,并在外层 div 中把此 model 绑定给另一个显示区域,内层改变时,外层不会同步改变,因为此时已经是两个变量了。

针对第二点,如果想传递给外层的model,则在ng-if的ng-model中加一个$parent即可,如下:

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">
“父级”环境
<input type="text" ng-model="parentVal"><br><br><br><br>
<div ng-if="parentVal == 'a'" style="border:1px solid #ccc;width:200px;height:200px;margin:20px">
"子"环境
<input type="text" ng-model="childVal"></br>
内层显示ng-if的model: {{childVal}}
</div>

在外层显示ng-if中的model: {{childVal}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

});
</script>

</body>
</html>


  

参考网址:http://blog.csdn.net/sinat_31057219/article/details/60780479
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: