如何销毁angularjs应用程序?

CHS*_*CHS 29 angularjs

我需要能够动态加载/卸载角度应用程序而不会导致内存泄漏.在jQuery中你可以做到$("#elementHoldingMyWidget").remove();并且正确的破坏代码被执行,事件处理程序是未绑定的等等.

我一直无法在角度文档中找到任何内容,一旦它被引导就可能会删除应用程序.

我的第一次尝试是破坏rootScope,如下所示:

var rootScope = $("body").scope();   
rootScope.$destroy();
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用,我不确定注射器和服务如何清理,即使它确实如此.

该怎么做?

Klo*_*231 18

使用AngularJS 1.4.0,$ rootScope.$ destroy()再次工作(因为它在1.2中被破坏).使用此功能可以在几个angularJS应用程序之间切换:

var appManager = new function () {
    this.currentAppName;
    this.currentApp;

    this.startApp = function (appContainerId, appName) {
        if (this.currentApp) {
            this.destroyApp(this.currentApp, this.currentAppName);
        }
        var appContainer = document.getElementById(appContainerId);
        if (appContainer) {
            this.currentAppName = appName;
            this.currentApp = angular.bootstrap(appContainer, [appName]);
        }
    }

    this.destroyApp = function (app, appName) {
        var $rootScope = app.get('$rootScope');
        $rootScope.$destroy();
    }
}

// Call this when page is ready to rebootsrap app
appManager.startApp('divContainerId', 'app');
Run Code Online (Sandbox Code Playgroud)


Joh*_*der 10

要在不向用户显示白页的情况下拆除我的应用程序$('body').empty,我首先$delete()将子范围移除,然后从$rootScope以下位置删除所有属性:

/*
 * Iterate through the child scopes and kill 'em
 * all, because Angular 1.2 won't let us $destroy()
 * the $rootScope
 */
var scope = $rootScope.$$childHead;
while (scope) {
    var nextScope = scope.$$nextSibling;
    scope.$destroy();
    scope = nextScope;
}

/*
 * Iterate the properties of the $rootScope and delete 
 * any that possibly were set by us but leave the 
 * Angular-internal properties and functions intact so we 
 * can re-use the application.
 */
for(var prop in $rootScope){
    if (($rootScope[prop]) 
        && (prop.indexOf('$$') != 0) 
        && (typeof($rootScope[prop]) === 'object')) {
            $rootScope[prop] = null;
        }
}
Run Code Online (Sandbox Code Playgroud)


mlu*_*noe 0

2013 年 3 月 10 日更新:我发现 $('body').empty(); 不会拆除该应用程序。它还活着。

原帖:

好吧,这篇文章:https://github.com/angular/angular.js/issues/1537#issuecomment-10164971声称没有“官方”应用程序拆解(在撰写本文时),但您可以清空持有应用程序的元素如下所示:

$('body').empty();
Run Code Online (Sandbox Code Playgroud)

如果这不是您想要的,您可以通过以下步骤获取临时解决方案来拆除您的应用程序: https: //github.com/angular/angular.js/issues/1537#issuecomment-10184033

  • 顺便提一句。我发现 $('body').empty(); 不会拆除该应用程序。它还活着。 (5认同)