我想使用javascript动态创建角度组件,然后使用$compile新创建的范围进行角度编译.然后,当我不再使用该组件时,我想要销毁组件和新范围.
一切都按预期工作,除非我正在破坏新范围,它使用的所有内存永远不会被释放.
以下是该代码的简化版本的一部分:
app.controller("mainCtrl", ["$scope", "$compile", function($scope, $compile) {
var childScope;
//call this every time the button is clicked
this.createDirective = function() {
//dynamically create a new instance of the custom directive
var customDirective = document.createElement("custom-directive");
//if another child scope exists, destroy it
if (childScope) {
childScope.$destroy();
childScope = undefined;
}
//create a new child scope
childScope = $scope.$new();
//compile the custom directive
$compile(customDirective)(childScope);
};
}]);
Run Code Online (Sandbox Code Playgroud)
这个代码的完整工作示例在这里
所有这些代码都是在每次单击按钮时创建一个新组件,但首先销毁已存在的任何组件.请注意,我实际上并没有在页面中添加已编译的组件,因为我注意到无论是否使用它,泄漏仍然存在.
使用Chrome的开发工具(配置文件 - >记录分配时间轴 - >开始)我在点击按钮几次后看到以下内存使用情况:
很明显,即使$destroy调用了作用域的函数,customDirective占用的任何内存也从未实际释放过. …