我在ng-view上安装了一个angular应用程序。在一个视图中,除了视图本身之外,该视图内部还有一个动态加载的组件。这个组件是一个指令,它本质上编译内容,因此内容可以进一步与其他指令挂钩(它确实是这样的)。该组件中的内容是使用$compile(element.contents())(scope);编译的。
举个例子:
<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);
}
);
};
}]);我的问题是,当我切换路由时,我本质上切换了ng-view或viewer的内容,我遇到的问题是内存泄漏,在viewer内部的其他指令中挂接到事件,并且在路由更改时没有清理。
下面是一个这样的例子:
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();
});
}
};
}]);我如何拥有它,以便这些事件得到适当的清理?
发布于 2013-06-20 07:44:47
如果您只使用一次,那么您提供的i18n示例将会起作用。
我不认为你应该在编译函数中进行事件绑定。您可以在link函数中执行此操作:
angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
return {
restrict: 'EAC',
link: function(scope, element, attrs) {
var cleanup;
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));
});
scope.$on('$destroy', function() {
console.log("destroy");
cleanup();
});
}
};
}]);或者,您可以在子范围本身上绑定事件,并在$rootScope上使用$broadcast来触发它。这样,当作用域被销毁时,事件将自动被垃圾回收:
angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
return {
restrict: 'EAC',
link: function(scope, element, attrs) {
var originalText = element.text();
setElText();
function setElText(locale){
element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
}
scope.$on('locale-changed', setElText);
}
};
}]);
$rootScope.$broadcast('locale-change', 'en-AU');https://stackoverflow.com/questions/17203005
复制相似问题