Ng-如果在角度js中导致内存泄漏! 图片:https://www.mediafire.com/?ojoc55ccnyqlxyb
我的应用有两页
第一页是显示搜索输入的主页
第二页是释放内存的empy页面。
我是如何检测泄漏的?
从链接运行我的应用:http://www.mediafire.com/download/y5f6f326f3zo0ch/LeakProject_-_Copy.7z
在匿名模式下使用铬,F12 - >个人资料 - >记录堆分配。
点击主页后点击主页,重复更多时间,结果没有任何泄漏。
我发现,当转到空白页面时,主页中的ovNgListBox范围将会破坏。 我认为scope.textSearch的值将更改为undefined和$ scope。$ watch in ng-if of angualr.js将执行以销毁范围。但反之亦然: 虽然html范围
<ov-ng-list-box class="ng-isolate-scope"><div ng-init="showFilter=true" class="pull-right">
但
的范围 <input type="text" ng-model="textSearch" ng-if="showFilter" placeholder="please type here to search..." class="search ng-scope ng-pristine ng-valid">
没有被破坏。为什么?
即使您将scope.showFilter的值更改为false,然后将$ scope更改为$ watch of in-if not called。
摘录代码:
// templateleak.html <br/>
<div class="pull-right" ng-init="showFilter=true" >
<input type="text" class="search" placeholder="please type here to search..." ng-if="showFilter" ng-model="textSearch"/>
</div>
// my directive
app.directive('ovNgListBox', [function () {
return {
restrict: 'AE',
scope: {},
templateUrl: 'views/template/templateLeak.html',
controller: ['$scope',function(scope){
console.log("Im in link of directive");
scope.textSearch='';
scope.search = function(){};
scope.$on('$destroy', function(){
scope.showFilter=false;
});
}]
};
}])
//angular.js
var ngIfDirective = ['$animate', function($animate) {
return {
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function ($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (toBoolean(value)) {
if (!childScope) {
//
答案 0 :(得分:1)
使用清理功能清除angular.element对象:
function dealoc(obj)
{
var jqCache = angular.element.cache;
if (obj)
{
if (angular.isElement(obj))
{
cleanup(angular.element(obj));
}
else if (!window.jQuery)
{
// jQuery 2.x doesn't expose the cache storage.
for (var key in jqCache)
{
var value = jqCache[key];
if (value.data && value.data.$scope == obj)
{
delete jqCache[key];
}
}
}
}
function cleanup(element)
{
element.off().removeData();
if (window.jQuery)
{
// jQuery 2.x doesn't expose the cache storage; ensure all element data
// is removed during its cleanup.
jQuery.cleanData([element]);
}
// Note: We aren't using element.contents() here. Under jQuery, element.contents() can fail
// for IFRAME elements. jQuery explicitly uses (element.contentDocument ||
// element.contentWindow.document) and both properties are null for IFRAMES that aren't attached
// to a document.
var children = element[0].childNodes || [];
for (var i = 0; i < children.length; i++)
{
cleanup(angular.element(children[i]));
}
}
}
<强>参考强>