2014-10-01 89 views
2

这是我的问题:我想创建一个单页面应用程序,当点击菜单的不同条目时,AngularJS应用程序可以在“主要内容”部分中随时加载/卸载。用angular.bootstrap手动加载/卸载模块?

但我只是不知道如何做到这一点。当使用angular.bootstrap函数时,我总是得到ng:btstrpd错误。

我用下面的代码加载应用程序:

var mainContent = document.getElementById('main-content'); 
window.loadApp = function(modules) { 
    angular.bootstrap(mainContent, modules); 
} 

这里是一个的jsfiddle:http://jsfiddle.net/010b62ry/

我试图删除DOM元素,再重新插入,但我得到奇怪的行为(如重复) 。我认为这些模块并未卸载。 我也有这么多的<!-- ngView: -->评论。

任何人都有关于如何实现这个好主意?如果在从一个应用程序切换到另一个应用程序时释放内存,则为奖励点。 PS:我真的需要引导100%独立模块(管理自己的路由等),因为其中一些模块可能由无法访问此应用源代码的其他人开发。我只需要将它们的模块作为100%自主角度应用程序启动。

+0

可能不是密切相关的,我有一个问题发布某个时候返回一个不同的问题。它有一个演示..不知道可能会提供一些线索.. http://stackoverflow.com/questions/25537396/override-angular-services-during-config-phase-for-live-mock-feature-with-the- SAM – PSL 2014-10-01 17:09:41

回答

2

我发现此线程How to destroy an angularjs app?。虽然我添加了代码来重新创建main-content div。

HTML代码:

<nav> 
    <a onclick="loadApp(['app1'])">Load app n°1</a> 
    <a onclick="loadApp(['app2'])">Load app n°2</a> 
</nav> 
<div id="main-content-wrap"> 
    <div id="main-content" class="app"> 
     <div ng-view></div> 
    </div> 
</div> 

JS:

angular.module('app1', ['ngRoute']); 
angular.module('app1') 
.config(['$routeProvider', function ($routeProvider) { 
    $routeProvider 
    .otherwise({ 
     template: 'hello app n°1' 
    }); 
}]); 
angular.module('app2', ['ngRoute']); 
angular.module('app2') 
.config(['$routeProvider', function ($routeProvider) { 
    $routeProvider 
    .otherwise({ 
     template: 'hello app n°2' 
    }); 
}]); 

var mainContent = document.getElementById('main-content'); 
var mainContentWrap = document.getElementById('main-content-wrap'); 
var mainContentHTML = mainContentWrap.innerHTML; 
window.loadApp = function(modules) { 
    if (window.currentApp) { 
     destroyApp(window.currentApp); 
     mainContentWrap.removeChild(mainContent); 
     mainContentWrap.innerHTML = mainContentHTML; 
     mainContent = document.getElementById('main-content'); 
    } 
    window.currentApp = angular.bootstrap(mainContent, modules); 
} 

function destroyApp(app) { 
    /* 
* Iterate through the child scopes and kill 'em 
* all, because Angular 1.2 won't let us $destroy() 
* the $rootScope 
*/ 
    var $rootScope = app.get('$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; 
     } 
    } 
} 

和小提琴http://jsfiddle.net/010b62ry/5/

它的工作原理,但它看起来像一个黑魔法。我认为拥有一个应用程序和多个控制器会更好。