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

Commit

Permalink
fix(ng-switch): properly destroy child scopes
Browse files Browse the repository at this point in the history
  • Loading branch information
IgorMinar committed Mar 14, 2012
1 parent 8fd1b74 commit 2315d9b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/directive/ngSwitch.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,21 @@ var ngSwitchDirective = valueFn({
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement;
selectedElement,
selectedScope;

scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = null;
selectedElement = selectedScope = null;
}
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedTransclude(scope.$new(), function(caseElement, scope) {
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
element.bind('$destroy', bind(scope, scope.$destroy));
});
}
});
Expand Down
30 changes: 30 additions & 0 deletions test/directive/ngSwitchSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,34 @@ describe('ng-switch', function() {
expect($rootScope.name).toEqual('works');
expect(element.text()).toEqual('works');
}));


it('should properly create and destory child scopes', inject(function($rootScope, $compile) {
element = $compile(
'<ng:switch on="url">' +
'<div ng-switch-when="a">{{name}}</div>' +
'</ng:switch>')($rootScope);
$rootScope.$apply();

var getChildScope = function() { return element.find('div').scope(); };

expect(getChildScope()).toBeUndefined();

$rootScope.url = 'a';
$rootScope.$apply();
var child1 = getChildScope();
expect(child1).toBeDefined();
spyOn(child1, '$destroy');

$rootScope.url = 'x';
$rootScope.$apply();
expect(getChildScope()).toBeUndefined();
expect(child1.$destroy).toHaveBeenCalledOnce();

$rootScope.url = 'a';
$rootScope.$apply();
var child2 = getChildScope();
expect(child2).toBeDefined();
expect(child2).not.toBe(child1);
}));
});

0 comments on commit 2315d9b

Please sign in to comment.