在Angular模块创建后添加依赖项

dem*_*isx 24 angularjs

你们知道在创建之后是否可以添加模块依赖项?像这样的东西:

// init module in file A
angular.module("myApp", []);

// retrieve module in file B and add new dependencies:
mod = angular.module("myApp");
// now I want to add an 'ngResource' dependency to mod
// ???
Run Code Online (Sandbox Code Playgroud)

编辑:我理解这似乎是一个奇怪的问题.我正在开发基于组件的应用程序组织,并且想要查看子组件是否可以向其父组件模块添加依赖项,而无需定义自己的模块.像这样的东西:

app/
 components/
   |__componentA/ 
        |__app.js // initializes component A module
        |__subcomponentA/ 
              |__app.js // want to add subcomponentA dependencies to componentA module from here
Run Code Online (Sandbox Code Playgroud)

我的替代方案是直接在componentA模块上声明所有subcomponentA依赖项,但从组织的角度来看,我更喜欢将这些依赖项保留在subcomponentA目录中,所以如果我后来决定从应用程序中删除子组件A,我不会需要记住从componentA模块中删除其依赖项.我希望将与subcomponentA有关的所有内容分组到subcomponentA目录中.我的构建脚本将确保在子组件A之前处理componentA代码.

感谢所有对此进行抨击的人.

sha*_*hah 34

我使用以下方法,并为我工作正常.

var app = angular.module("myApp", []);

angular.module("myApp").requires.push('ngResource');
Run Code Online (Sandbox Code Playgroud)


小智 0

我认为这是不可能的。然而,我很乐意被证明是错误的。

根据我的经验(并且根据Angular 文档),模块依赖项只能在初始化模块时声明。值得注意的是,在应用程序启动之前,依赖关系尚未完全设置。据我所知,不可能向正在运行的应用程序添加依赖项,除非有一种方法可以重新启动整个应用程序,无论如何这可能会产生不需要的副作用。

编辑:实际上......我从来没有尝试过这个,但这实际上可能比我最初想象的要简单得多。我们可以尝试以下方法:

文件A:

window.myApp_dependencies = []; // Add dependencies to the global scope.

angular.module('myApp', dependencies);
Run Code Online (Sandbox Code Playgroud)

文件B:

var mod = angular.module("myApp");

window.myApp_dependencies.push('ngRoute');
Run Code Online (Sandbox Code Playgroud)

这并不是很理想,因为您被迫在全局范围内创建变量。不过,可以通过模块来实现。请注意,在这种情况下,依赖项只能在应用程序实际启动之前可变 - 因此,您可以跨文件拆分依赖项,但无法在运行时更改它们。

我不知道这是否有效。不过我明天要尝试一下。