(简单的 plunkr 演示 here)
使用 ng-repeat 在第二波之后迭代自定义对象的“数组”时存在泄漏,如下所示:
<div ng-repeat="d_sampleObject in mySampleObjects">
{{d_sampleObject.description}}
</div>
内存配置文件显示遗留了一个额外的“d_sampleObject”并且未取消引用。下面有更多详细信息(通过 Controller 和注入(inject)服务)。在提供的 plunkr 链接中也有一个简单的演示。提前非常感谢任何想法和帮助!
注意“mySampleObjects”是以下实例的数组:
ml.MySampleObject = function (id) {
this.id = id;
this.description = 'this is object #:' + ' '+id;
}
我有一个自定义对象模型,它反射(reflect)了我们在 AngularJS 应用程序中使用的业务领域对象。我发现当我将我的自定义对象之一的实例传递给 ng-repeat 时,会保留对它的引用(我认为是 Angular)并且不会释放内存。这发生在 ng-repeat 的第二个“wave”(点击“刷新”)上,因为它再次迭代其对象数组。此泄漏在我的配置文件测试(在 Chrome 中)中暴露出来。 Here是 plunkr 中的一个简短示例。单击“刷新”按钮一次(或多次)以查看泄漏的额外“d_sampleObject”对象实例(在 Chrome 配置文件检查中)。请注意,“d_sampleObject”名称仅在传递给 ng-repeat 时使用。我在下面包含了正在进一步泄露的额外对象实例 ('d_sampleObject') 的屏幕截图。为什么会出现泄漏,如何避免?
(请注意,我发现如果我不通过对象而是通过原始索引(“整数”)遍历我的对象集合(JS 数组),则不会发生泄漏。泄漏似乎只发生在我使用对象引用作为 ng-repeat 迭代的结果)
<!DOCTYPE html>
<html ng-app="memoryleak">
<head>
<meta charset="utf-8" />
<title>Memory Leak Test</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.13/angular.min.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
<script src="dataservice.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="d_sampleObject in mySampleObjects">
{{d_sampleObject.description}}
</div>
<br>
<button ng-click="redo()">Number of refreshes: {{numRedos}}!</button>
</body>
</html>
(function(ml) {
var app = angular.module('memoryleak',['servicemodule']);
app.controller('MainCtrl', ['$scope', 'dataservice', function($scope, dataservice) {
$scope.redo = function () {
$scope.numRedos++;
$scope.mySampleObjects = dataservice.myObjectCollection;
dataservice.redo();
}
$scope.redo();
}]);
}(window.MEMLEAK = window.MEMLEAK || {}));
(function(ml) {
'use strict';
var serviceModule = angular.module('servicemodule',[]);
serviceModule.factory('dataservice', ['$rootScope', '$http',
function ($rootScope, $http) {
this.myObjectCollection = [];
this.redo = function () {
this.numRedos++;
// that.myObjectCollection = [];
this.myObjectCollection.length = 0;
for (var i = 0; i < 10; i++) {
var sampleObject = new ml.MySampleObject(i);
that.myObjectCollection.push(sampleObject);
}
sampleObject=null;
}
ml.MySampleObject = function (id) {
this.id = id;
this.description = 'this is object #:' + ' '+id;
}
return this; //return the entire service to make methods accessible to dependents
}]);
}(window.MEMLEAK = window.MEMLEAK || {}));
屏幕截图 1:(第一页加载——创建了 10 个“mySampleObjects”)
屏幕截图 2:(点击刷新——创建/泄露了第 11 个 mySampleObject,其中引用了传递给 ng-repeat 的“d_sampleObject”的实例名称。)
最佳答案
有acknowledgement AngularJS 的人认为这确实是框架中的一个错误。修复和拉取请求已 posted .
我还询问了正式修复的时间范围。
关于javascript - Angular : Memory Leak with ng-repeat using custom objects (w/simple PLUNKR),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28683992/