My angular application has been configured with the use of ng-view
. Within one specific view, there is a dynamically loaded component alongside the view itself. This component acts as a directive that compiles its contents to allow for further interaction with other directives. The content within this component is compiled using
$compile(element.contents())(scope);
.
For example:
<ng-view>
<viewer doc="getDocument()">
</viewer>
</ng-view>
angular.directive('viewer', ['$compile', '$anchorScroll', function($compile, $anchorScroll) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
var doc = scope.$eval(attrs.doc);
if (!doc)
return ""
return doc.html;
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}]);
The issue I am facing arises when switching routes, causing a switch in the content of either ng-view
or viewer
. This problem leads to a memory leak, where certain directives within the viewer
continue to hold onto events and do not clean up properly upon route change.
An example of such a directive is shown below:
angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
var cleanup;
return {
restrict: 'EAC',
compile: function(element, attrs) {
var originalText = element.text();
element.text(LocaleService.getTranslation(originalText, attrs.locale));
cleanup = $rootScope.$on('locale-changed', function(locale) {
element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
});
},
link: function(scope) {
scope.$on('$destroy', function() {
console.log("destroy");
cleanup();
});
}
};
}]);
What steps can be taken to ensure these events are properly cleaned up?