Reputation: 41
I have a directive that dynamically adds child custom directives to the DOM based on some input. Everything works fine. But when the input changes and I re-render the DOM with a different set of child custom directives, the old scopes of the child custom directives are not deleted and hence, the event handlers attached to them are still in memory.
I am re-rendering the DOM by just setting element[0].innerHTML = ''. Is there a way to delete/destroy the scopes of the custom directive? I saw in some articles that scope.$destroy can be called but how to get a reference of the scope of the child custom directive?
const linker = function (scope, element) {
scope.$watch('data', function () {
reRenderToolbar();
}, true);
const reRenderToolbar = function () {
element[0].innerHTML = '';
_.forEach(scope.data, function (item, key) {
const directive = item.CustomDirective;
scope.options = item.options || {};
html = '<' + directive + ' options="options"></' + directive + '>';
element.append(html);
}
});
}
$compile(element.contents())(scope);
};
Upvotes: 1
Views: 367
Reputation: 41
The issue was that I was not destroying the childscope in the parent as my app is multiscoped. This article helped me http://www.mattzeunert.com/2014/11/03/manually-removing-angular-directives.html Code:
const linker = function (scope, element) {
scope.$watch('data', function () {
reRenderToolbar();
}, true);
let childScope;
const reRenderToolbar = function () {
if(childScope) {
childScope.$destroy();
}
element[0].innerHTML = '';
_.forEach(scope.data, function (item, key) {
const directive = item.CustomDirective;
scope.options = item.options || {};
html = '<' + directive + ' options="options"></' + directive + '>';
element.append(html);
}
});
}
childScope = scope.$new()
$compile(element.contents())(childScope);
};
Upvotes: 3
Reputation: 1021
on your custom directive handle the destroy event
directive("CustomDirective", function(){
return {
restrict: 'C',
template: '<div >Custom Directive</div>',
link: function(scope, element){
scope.$on("$destroy",function() {
element.remove();
});
}
}
});
Upvotes: 1