Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 9483373

Browse files
committed
fix(ngIf): destroy child scope when destroying DOM
1 parent c6923d2 commit 9483373

File tree

2 files changed

+40
-12
lines changed

2 files changed

+40
-12
lines changed

src/ng/directive/ngIf.js

+19-11
Original file line numberDiff line numberDiff line change
@@ -87,23 +87,31 @@ var ngIfDirective = ['$animate', function($animate) {
8787
$$tlb: true,
8888
compile: function (element, attr, transclude) {
8989
return function ($scope, $element, $attr) {
90-
var block = {}, childScope;
90+
var block, childScope;
9191
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
92-
if (block.startNode) {
93-
$animate.leave(getBlockElements(block));
94-
block = {};
95-
}
96-
if (block.startNode) {
97-
getBlockElements(block).$destroy();
98-
block = {};
99-
}
92+
10093
if (toBoolean(value)) {
94+
10195
childScope = $scope.$new();
10296
transclude(childScope, function (clone) {
103-
block.startNode = clone[0];
104-
block.endNode = clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
97+
block = {
98+
startNode: clone[0],
99+
endNode: clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ')
100+
};
105101
$animate.enter(clone, $element.parent(), $element);
106102
});
103+
104+
} else {
105+
106+
if (childScope) {
107+
childScope.$destroy();
108+
childScope = null;
109+
}
110+
111+
if (block) {
112+
$animate.leave(getBlockElements(block));
113+
block = null;
114+
}
107115
}
108116
});
109117
};

test/ng/directive/ngIfSpec.js

+21-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ describe('ngIf', function () {
3636
expect(element.children().length).toBe(0);
3737
});
3838

39-
it('should create a new scope', function () {
39+
it('should create a new scope every time the expression evaluates to true', function () {
4040
$scope.$apply('value = true');
4141
element.append($compile(
4242
'<div ng-if="value"><span ng-init="value=false"></span></div>'
@@ -45,6 +45,26 @@ describe('ngIf', function () {
4545
expect(element.children('div').length).toBe(1);
4646
});
4747

48+
it('should destroy the child scope every time the expression evaluates to false', function() {
49+
$scope.value = true;
50+
element.append($compile(
51+
'<div ng-if="value"></div>'
52+
)($scope));
53+
$scope.$apply();
54+
55+
var childScope = element.children().scope();
56+
var destroyed = false;
57+
58+
childScope.$on('$destroy', function() {
59+
destroyed = true;
60+
});
61+
62+
$scope.value = false;
63+
$scope.$apply();
64+
65+
expect(destroyed).toBe(true);
66+
});
67+
4868
it('should play nice with other elements beside it', function () {
4969
$scope.values = [1, 2, 3, 4];
5070
element.append($compile(

0 commit comments

Comments
 (0)