如何动态地将模块注入主Angular app模块

use*_*634 12 angularjs

我没有在单页面应用程序上使用角度,但是由于加载顺序问题,我想定义主应用程序模块一次.同时我想在每页上注入/需要模块而不是毯子,因为并非所有JS文件都会被加载到每个页面上.

我可以定义没有必需模块的应用程序:

app = angular.module("app",[])

让它们从控制器或后期注入?

Tia*_*dão 24

在我阅读你的问题之后,我可以想到一个可能的解决方案/黑客.

我们的想法是在包含任何模块之前定义一个依赖关系数组,并在每个模块中添加它:

// before anything else
window.loadedDependencies = [];

// at the end of each module file:
window.loadedDependencies.push('moduleName')

// after all that, at the app definition:
app = angular.module("app", loadedDependencies)
Run Code Online (Sandbox Code Playgroud)

老实说,我并没有真正考虑过这种方法可能带来的任何影响/复杂性,而且在我做之前我无法真正保证这一点(为什么对脚本文件的调用和缓存对你的用例有好处? )


pko*_*rce 8

不,目前尚未正式支持.在引导AngularJS应用程序之前,必须在浏览器中加载所有模块(并声明为主应用程序模块的依赖项).


tk1*_*404 7

我们可以通过使用来实现它 app.requires

//app.js
    var app = angular.module('myngapp',['ngRoute','ngCookies','ui.bootstrap','kendo.directives','pascalprecht.translate','tmh.dynamicLocale']);

    app.config(['$routeProvider', '$httpProvider', '$translateProvider', 'tmhDynamicLocaleProvider', '$compileProvider', function($routeProvider, $httpProvider, $translateProvider, tmhDynamicLocaleProvider, $compileProvider) {
    'use strict';

    $compileProvider.debugInfoEnabled(false);

    $routeProvider.otherwise({
        redirectTo: '/login'
    });
    }]);
Run Code Online (Sandbox Code Playgroud)

在myModule.js中

  app.requires.push('app.myModule');
Run Code Online (Sandbox Code Playgroud)

在index.html中,包括第app.js一个和myModule.js下一个.通过这种方式,您可以包含n个模块而无需修改app.js.

从app.js中包含myModule.js

var mainHead = document.getElementsByTagName('HEAD').item(0);
var myScript= document.createElement("script");
myScript.type = "text/javascript";
mainHead.appendChild( myScript);
myScript.src='../myModule.js';
myScript.onload = function(){
     angular.element(document).ready(function() {
                      angular.bootstrap(document, ['myngapp']);
                     });
     }
Run Code Online (Sandbox Code Playgroud)

注意:这里我们手动引导应用程序,以便动态加载的模块也包含在我们的应用程序中


Ash*_*rke 6

使用Tiago的好主意(upvote他!),我的模块中有以下内容:

window.dependencies = _.union(window.dependencies || [], [
    "ngRoute",
    "app.mymodule1"
]);

angular
    .module("app.mymodule1", [])
    .config(["$routeProvider", function ($routeProvider) {
        // more code
    }]);
Run Code Online (Sandbox Code Playgroud)

这在我的app.js:

var app;

window.dependencies = _.union(window.dependencies || [], [
    "ngRoute",
    "app.anothermodule"
]);

window.app = app = angular.module("app", window.dependencies);
Run Code Online (Sandbox Code Playgroud)

我使用LoDash,因此我将依赖项联合起来以获取一组唯一值 - 我的一些模块使用与app.js例如相同的依赖项ngRoute.

我的脚本包含在body标签的底部,如下所示:

<!-- scripts from other pages/modules included here -->

<script src="/js/anothermodule/anothermodule.js"></script>
<script src="/js/app.js"></script>
Run Code Online (Sandbox Code Playgroud)

奇迹般有效!

我的页面共享一个"主"页面,但我在自己的文件中有模块定义,所以我需要这样的东西.