【发布时间】:2017-04-19 02:42:10
【问题描述】:
我创建了一个可以显示多页项目的列表模块。我正在使用嵌套的 ng-repeat 来遍历页面和每个页面上的项目。但是,我注意到当我不断刷新列表并加载新页面和项目时,Chrome Timeline 工具中的 DOM 节点不断增加,内存使用量也在增加(我确保在录制过程中单击了垃圾收集按钮,所以必须有东西泄漏):
我正在使用 angular 1.5.5 和 requireJS,我听说 ng-repeat 曾经有内存泄漏,但在 1.4.x 中已经修复。代码很简单,我没有在代码中注册任何 DOM 处理程序,我已经研究了一周,仍然无法弄清楚原因,我现在非常绝望,非常感谢帮助。
我的代码文件结构是这样的:
list-container
|___module.js
|
|___controllers
| |____list-container.js
|
|___directives
| |____list-container.js
|
|___views
|____directive-list-container.html
下面是代码:
模块.js
define([
'angular',
], function (angular) {
'use strict';
return angular.module('ui.listContainer', []);
});
list-container.js(指令)
define([
'angular',
'../module',
'../controllers/list-container'
], function (angular, module) {
'use strict';
return angular
.module('ui.listContainer')
.directive('listContainer', function () {
return {
replace: true,
restrict: 'E',
templateUrl: '/modules/list-container/views/directive-list-container.html',
bindToController: {},
scope: {},
controllerAs: 'listVm',
controller: 'listContainerController'
};
});
});
list-container.js(控制器)
define([
'angular',
'../module'
], function (angular, module) {
'use strict';
angular.module('ui.listContainer').controller('listContainerController', ['$scope', function ($scope) {
var listVm = this;
$scope.refreshPage = function () {
if (listVm.list) {
listVm.list = null; //Clear the data
}
listVm.list = {};
listVm.list.pages = feedData(); //Load mock data
};
function feedData() {
var pages = [];
for(var i = 0; i < 10; i++) {
pages.push(new PageMock());
}
return pages;
}
function PageMock() {
this.items = [];
for (var i = 0; i < 50; i++) {
this.items.push(new ItemMock());
}
}
function ItemMock() {
this.id = Math.floor(Math.random() * 10000000);
}
}]);
});
directive-list-container.html(视图)
<div class="list-container row">
<div id="list-container-pages">
<div class="list-container-pages row">
<div ng-click="refreshPage()">Refresh Page</div>
<div class="list-container-page row" ng-repeat="page in listVm.list.pages track by $index">
<div class="row" ng-repeat="listItem in page.items track by listItem.id">
<span class="col-md-12">{{listItem.id}}</span>
</div>
</div>
</div>
</div>
</div>
我创建了一个 plunker 来模仿我上面的代码,但是在 plunker 示例中它根本没有泄漏,这非常奇怪。 Plunker Example
【问题讨论】: