I have an angular app setup with ng-view
. In one view, in addition to the view itself, there is also a component inside that view that is dynamically loaded. This component is a directive that essentially compiles the contents so the contents can be further hooked with other directives (which it is). The content inside that component is compiled using $compile(element.contents())(scope);
.
As an 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);
}
);
};
}]);
My problem is when I switch routes, I essentially switch ng-view
or viewer
's content. The problem I'm having is a memory leak, where in other directives inside the viewer
hooks to events and do not clean up when the route is changed.
One such example is as follows:
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();
});
}
};
}]);
How do I have it so that these events are properly cleaned up?
question from:
https://stackoverflow.com/questions/17203005/angularjs-directive-destroy 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…