I have a directive that does the following:
As others have answered, the short solution is to use
ng-show instead of
ng-if or to not use
$compile like that. With that aside, you might have your good reasons why you would want to use
$compile like this.
This question interested me on the note of using
$compile with an isolate scope from
ng-if. I did a bit of experimenting with this fork and will try to explain what I found.
We already know
ng-if creates an isolate scope, but then passing that element with
ng-if on it through
$compile creates another isolate scope (and would make the newly compiled
ng-if be looking at variables on the first-round isolate scope - the directive's
To re-iterate that, we're having some scopes looking like (value in  is scope.$id):
main/outer controller has
ng-if my-test element has
ng-if looking at
scope.count and creates
my-test linker therefore has
$scope.$id == 3;
$compile - recompiled
ng-if element: creates new isolate
scope and is looking at
scope.count hits 0 -
scope was created by that first
ng-if which is still lingering around somewhere) ... BUT! the element is A. still there and B. its count isn't updating - WHY?
Well because the element that's still there is the one that was
$compiled and has A. an
ng-if looking at
scope.count (which is now $destroyed) and B. its own new isolate
scope (created by re-compiling
ng-if element with parent
So ya. That is all very confusing and you might just be asking... well how do I fix this??
The simplest solution:
$element.removeAttr('ng-if'); before you do
If you've been following along, this works because the original
ng-if is still looking at
scope.count, and the element that is present is no longer getting a second isolate scope.