我正在开发一个使用angularjs-nvd3-directives来呈现图表的angularjs应用程序。
在检查了一下Chrome开发人员工具后,我发现了一些与图表相关的内存泄漏。当用户在包含图表的不同视图中导航时,内存永远不会完全释放。
我已经在图形控制器上做了一些清理:
$scope.$on('$destroy', function() {
d3.select( '#exampleId' ).remove();
d3.select( '#exampleId2' ).remove();
...
});在routeChange事件上:
myApp.run(function($rootScope, $templateCache) {
//try to clear unused objects to avoid huge memory usage
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (typeof(current) !== 'undefined'){
//destroy all d3 svg graph
d3.selectAll('svg').remove();
nv.charts = {};
nv.graphs = [];
nv.logs = {};
}
});
});当我从我的应用程序中删除图表时,内存使用率总是回到初始值。
使用该图:

没有的话:

有没有其他方法来释放由这些图表生成的内存?
jsfiddle来演示此问题。
发布于 2014-09-10 20:04:59
您可能会忘记删除窗口调整大小侦听器。
angularApp.run(function($rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (typeof(current) !== 'undefined'){
//destroy d3 stuff
window.nv.charts = {};
window.nv.graphs = [];
window.nv.logs = {};
// and remove listeers for onresize.
window.onresize = null;
}
});
}); 您也可以尝试删除整个svg元素,但这似乎不是最好的方法。
发布于 2015-01-06 20:13:44
github也有类似的问题:https://github.com/cmaurer/angularjs-nvd3-directives/issues/193
正如我在那里解释的那样,下面的方法效果更好:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
angular.element(document.body.querySelectorAll('.nvd3')).remove();这解决了SVG内存泄漏问题。但是在数据端(数组)仍然有一些内存泄漏。
发布于 2014-10-29 18:14:39
我建议您将图移动到您自己的指令,它将保存其模板上的nvd3指令,并监听每个指令的作用域。
$destroy还会销毁此事件中的元素。
控制器应检索数据并将其分配给指令。
您可能想要监听指令上的$routeChangeStart,因此清理将被封装在使用数据的部分上。这样你就可以避免重复的代码。
我使用这种技术来清理使用模态的指令,这样就不会有重复的事件、侦听器或ids。
https://stackoverflow.com/questions/24821354
复制相似问题