我在下面有一个指令,想知道当组件从DOM中删除时是否会导致内存泄漏。如果JS / Angular GC能够解决这个问题,我不知道Angular在引擎盖下做了多少蠢事。 (我仍然试图了解Chrome Tools中的JS Profiler,以便能够自己解决这个问题)。那么,有这种经验的人可以回答这个问题吗?
angular.module('myApp')
.directive('myDir', [function() {
return {
restrict: 'AE',
replace: true,
scope: {
someEvent:'@'
},
transclude: 'element',
template: function(tElement, tAttrs) {
return '<div class="">' +
'<div ng-transclude ng-click="blah()" class=""></div>'
'</div>';
},
link: function (scope, el) {
scope.doSomething = function(){
.....
}
scope.$on(scope.someEvent, scope.doSomething);
}
}
}]);
当从dom中删除元素时,上面的代码是否会导致内存泄漏?我的意思是我知道我可以轻松地增强这个以添加$ destroy事件:IE:
var unregister = scope.$on(scope.someEvent, scope.doSomething);
scope.$on("$destroy",function() {
unregister();
});
但是这个额外的步骤是必要的还是Angular会照顾到这个呢?
感谢您的帮助!
答案 0 :(得分:1)
您不需要执行该步骤,当范围被销毁时,其上的所有侦听器也将被销毁。