[英]Ng-if causing memory leak in angular js
Ng-如果在角度js中導致內存泄漏! 圖片: https : //www.mediafire.com/?ojoc55ccnyqlxyb
我的應用有兩頁
第一頁是顯示搜索輸入的主頁
第二頁是empy頁面釋放內存。
我是怎么發現泄漏的?
從鏈接運行我的應用程序: http : //www.mediafire.com/download/y5f6f326f3zo0ch/LeakProject_-_Copy.7z
在匿名模式下使用chrome,F12 - > Profile - > Record Heap Allocation。 點擊主頁后點擊主頁,重復更多時間,結果沒有任何泄漏。
我發現,當轉到空白頁面時,主頁中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) {
//
使用清理函數清除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]));
}
}
}
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.