Is there a way to inject a late dependency to an already bootstrapped angular module? Here's what I mean:
Say that I have a site-wide angular app, defined as:
// in app.js var App = angular.module("App", []);
And in every page:
<html ng-app="App">
Later on, I'm reopening the app to add logic based on the needs of the current page:
// in reports.js var App = angular.module("App") App.controller("ReportsController", ['$scope', function($scope) { // .. reports controller code }])
Now, say that one of those on-demand bits of logic also requires their own dependencies (like ngTouch
, ngAnimate
, ngResource
, etc). How can I attach them to the base App? This doesn't seem to work:
// in reports.js var App = angular.module("App", ['ui.event', 'ngResource']); // <-- raise error when App was already bootstrapped
I realize I can do everything in advance, i.e -
// in app.js var App = angular.module("App", ['ui.event', 'ngResource', 'ngAnimate', ...]);
Or define every module on its own and then inject everything into the main app (see here for more):
// in reports.js angular.module("Reports", ['ui.event', 'ngResource']) .controller("ReportsController", ['$scope', function($scope) { // .. reports controller code }]) // in home.js angular.module("Home", ['ngAnimate']) .controller("HomeController", ['$scope', '$http', function($scope, $http){ // ... }]) // in app.js, loaded last into the page (different for every page that varies in dependencies) var App = angular.module("App", ['Reports', 'Home'])
But this will require I initialize the App everytime with the current page's dependencies.
I prefer to include the basic app.js
in every page and simply introduce the required extensions to each page (reports.js
, home.js
, etc), without having to revise the bootstrapping logic everytime I add or remove something.
Is there a way to introduce dependencies when the App is already bootstrapped? What is considered the idiomatic way (or ways) to do this? I'm leaning towards the latter solution, but wanted to see if the way I described could also be done. thanks.
I solved it like this:
reference the app again:
var app = angular.module('app');
then push your new requirements to the requirements array:
app.requires.push('newDependency');
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