用途
ng-if 属性用来控制页面内元素的添加或移除。
用法
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/> Show when checked: <span ng-if="checked">This is removed when the checkbox is unchecked.</span>
工作原理
本以为ng-if和ng-show/ng-hide类似(4行代码),单纯的进行元素的添加删除,然而ng-if要复杂得多,40多行代码 。子元素的ng事件,scope处理等。
ng-if 条件为true时,将所在元素的克隆添加到其父元素内,然后处理该元素以及内部所有子元素的ng事件;为false时,将其从父元素中移除,并且将其scope删除。
ngif的核心代码:
var block, childScope, previousElements; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (value) { if (!childScope) { $transclude(function(clone, newScope) { childScope = newScope;
$animate.enter(clone, $element.parent(), $element); }); } } else { if (previousElements) { previousElements.remove(); previousElements = null; } $animate.leave(previousElements).then(function() { previousElements = null; }); } });
常见问题
# 元素不随着指定的值进行添加或删除
<div ng-if="{{myValue}}" class="ng-hide"></div>
上述代码中ng-if 绑定的是{{}}表达式的值对应的字符串,而不是myValue。布尔型对应的是"" 空串 或者 "true" 。所以,myValue值变化后,对于ng-if而言,监视的是固定的字符串,没有变化。也就不会触发页面元素的添加或删除事件。