I am not using angular on a single page application however I would like to define the main app module once due to load order issues. At the same time I would like to inject/require modules on a per page basis and not blanket as not all JS files will be loaded on every page.
Can I define the app with no required modules:
app = angular.module("app", [])
and have them injected from a controller or at a later stage?
The root module is the main module in an Angular application. It is generated by the Angular CLI as AppModule and bootstrapped when the application starts. Every other Angular module depends either directly or indirectly on the root module. Only one root module can exist in an Angular application.
Sharing moduleslinkYou can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.
Every application has at least one Angular module, the root module, which must be present for bootstrapping the application on launch. By convention and by default, this NgModule is named AppModule . After the import statements is a class with the @NgModule decorator.
We can achieve it by using 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'
});
}]);
In myModule.js
app.requires.push('app.myModule');
and in your index.html, include the app.js
first and myModule.js
next. By this way, you can include n number of modules without modifying the app.js
.
Include the myModule.js on the fly from app.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']);
});
}
Note: here we are manually bootstrapping the application so that dynamically loaded modules are also included into our application
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With