如何卸载 angularjs 模块 [英] How to unload angularjs modules

查看:39
本文介绍了如何卸载 angularjs 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 N 个模块组成的应用程序.几乎所有这些模块都会按需加载.

I have an application that consists of N Modules. Almost all of those modules will be loaded on demand.

有没有什么好的方法可以用动态加载和卸载的模块来组织 AngularJS 应用程序?

Is there any good way to organize AngularJS application with dynamically loaded and unloaded modules?

  • 模块数 (N) 可以尽可能多,我不能保证它们的最大数量.所以我尽量避免过度使用内存;
  • 我不认为将代码保留在我们不打算使用的浏览器中是最佳做法(我不喜欢带有我的 web 应用程序的选项卡会消耗所有可用内存并挂起浏览器的想法);
  • 我认为 Google 太过分了.您可以全天使用 Gmail 并且它仍然正常运行(Google I/O 2013 - A Trip Down Memory Lane with Gmail and DevTools http://www.youtube.com/watch?v=x9Jlu_h_Lyw).

推荐答案

从 Angular 1.2.16 和 1.3.0 beta 开始,bootstrap() 方法 将 DOM 上的特定元素定义为模块集合的根范围.没有相应的解绑方法.ng-app 指令是 只是 bootstrap 的快捷方式(),所以同样的限制适用.

As of Angular 1.2.16 and 1.3.0 beta, the bootstrap() method defines a specific element on the DOM as the root scope for a collection of modules. There is no corresponding method to unbind. The ng-app directive is just a shortcut for bootstrap(), so the same limitation applies.

链接到的 angular-requirejs-seed 项目 Artemis 没有回答您的问题.它使用 NG_DEFER_BOOTSTRAP! 属性来暂停引导过程并在页面加载时动态定义要添加的模块.它不会卸载任何东西.

The angular-requirejs-seed project Artemis linked to does not answer your question. It uses the NG_DEFER_BOOTSTRAP! property to suspend the bootstrap process and dynamically define which modules to add at the time the page is loaded. It does not unload anything.

克服 Angular 固有的无法卸载模块的最直接方法是销毁运行模块的 DOM 元素.不幸的是,通过销毁元素,您也会丢失任何标记.该问题的一种解决方案是将应用程序的标记放入 HTML5 <template> 元素并克隆其内容.这是 我在 JSBin 中写的一个例子,其中一个名称含糊不清的 someGuyInASuit 指令根据加载的模块加载 Jekyll 博士或海德先生的图片.

The most straightforward way to overcome Angular’s inherent inability to unload modules is to destroy the DOM element where your modules are running. Unfortunately, by destroying the element, you also lose whatever markup you had. One solution to that problem is to put your app’s markup into an HTML5 <template> element and clone its contents. Here’s an example I wrote in JSBin where an ambiguously named someGuyInASuit directive loads a picture of Dr. Jekyll or Mr. Hyde depending on which module is loaded.

这种变通方法不太适合由许多模块组成的应用,尤其是当您打算在用户与其交互时频繁地将它们换入和换出时.一方面,您的所有模型都将被销毁.此外,所有 config()run() 块都将重新运行.您可能想要 fork Angular 并添加您自己的 un-bootstrap 方法,或者查看另一个框架,例如 React,它具有 一种卸载组件的方法 内置.

This work-around is not well suited to an app consisting of many modules, especially if you intend to swap them in and out frequently as the user interacts with it. For one, all your models will be destroyed. Also, all the config() and run() blocks will be re-run. You may want to either fork Angular and add your own un-bootstrap method or have a look at another framework such as React, which has a method for unloading components built in.

这篇关于如何卸载 angularjs 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆