Fact, that ng-if
directive, unlike ng-show
, creates its own scope, leads to interesting practical difference:
angular.module('app', []).controller('ctrl', function($scope){_x000D_
$scope.delete = function(array, item){_x000D_
array.splice(array.indexOf(item), 1);_x000D_
}_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app='app' ng-controller='ctrl'>_x000D_
<h4>ng-if:</h4>_x000D_
<ul ng-init='arr1 = [1,2,3]'>_x000D_
<li ng-repeat='x in arr1'>_x000D_
{{show}}_x000D_
<button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
<button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
<button ng-if='show' ng-click='show=!show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<h4>ng-show:</h4>_x000D_
<ul ng-init='arr2 = [1,2,3]'>_x000D_
<li ng-repeat='x in arr2'>_x000D_
{{show}}_x000D_
<button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
<button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
<button ng-show='show' ng-click='show=!show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<h4>ng-if with $parent:</h4>_x000D_
<ul ng-init='arr3 = [1,2,3]'>_x000D_
<li ng-repeat='item in arr3'>_x000D_
{{show}}_x000D_
<button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
<button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
<button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
At first list, on-click
event, show
variable, from innner/own scope, is changed, but ng-if
is watching on another variable from outer scope with same name, so solution not works. At case of ng-show
we have the only one show
variable, that is why it works. To fix first attempt, we should reference to show
from parent/outer scope via $parent.show
.