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

Commit 2315d9b

Browse files
committed
fix(ng-switch): properly destroy child scopes
1 parent 8fd1b74 commit 2315d9b

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

src/directive/ngSwitch.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -69,19 +69,21 @@ var ngSwitchDirective = valueFn({
6969
element.data(NG_SWITCH, cases);
7070
return function(scope, element){
7171
var selectedTransclude,
72-
selectedElement;
72+
selectedElement,
73+
selectedScope;
7374

7475
scope.$watch(watchExpr, function(value) {
7576
if (selectedElement) {
77+
selectedScope.$destroy();
7678
selectedElement.remove();
77-
selectedElement = null;
79+
selectedElement = selectedScope = null;
7880
}
7981
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
8082
scope.$eval(attr.change);
81-
selectedTransclude(scope.$new(), function(caseElement, scope) {
83+
selectedScope = scope.$new();
84+
selectedTransclude(selectedScope, function(caseElement) {
8285
selectedElement = caseElement;
8386
element.append(caseElement);
84-
element.bind('$destroy', bind(scope, scope.$destroy));
8587
});
8688
}
8789
});

test/directive/ngSwitchSpec.js

+30
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,34 @@ describe('ng-switch', function() {
6060
expect($rootScope.name).toEqual('works');
6161
expect(element.text()).toEqual('works');
6262
}));
63+
64+
65+
it('should properly create and destory child scopes', inject(function($rootScope, $compile) {
66+
element = $compile(
67+
'<ng:switch on="url">' +
68+
'<div ng-switch-when="a">{{name}}</div>' +
69+
'</ng:switch>')($rootScope);
70+
$rootScope.$apply();
71+
72+
var getChildScope = function() { return element.find('div').scope(); };
73+
74+
expect(getChildScope()).toBeUndefined();
75+
76+
$rootScope.url = 'a';
77+
$rootScope.$apply();
78+
var child1 = getChildScope();
79+
expect(child1).toBeDefined();
80+
spyOn(child1, '$destroy');
81+
82+
$rootScope.url = 'x';
83+
$rootScope.$apply();
84+
expect(getChildScope()).toBeUndefined();
85+
expect(child1.$destroy).toHaveBeenCalledOnce();
86+
87+
$rootScope.url = 'a';
88+
$rootScope.$apply();
89+
var child2 = getChildScope();
90+
expect(child2).toBeDefined();
91+
expect(child2).not.toBe(child1);
92+
}));
6393
});

0 commit comments

Comments
 (0)