AngularJS add dependencies after loading

I want to add dependencies after AngularJS boots up. I tried to do this through app.requires.push('app.main'); as suggested in this post ( reopen and add dependencies to an already downloaded application ). However, this does not work.

Here is my sample code:

index.html

 <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css"> <script type="text/javascript" src="https://code.angularjs.org/1.4.3/angular.min.js"></script> <script src="script.js"></script> </head> <body> <h1>Hello Plunker!</h1> </body> </html> 

script.js

  var app = angular .module('app',[]) .run(function($http){ $http.get("script2.js").success(function(data){ eval(data); //app.requires.push('app.main'); }).error(function(){ alert("error"); }); }); 

script2.js

 alert("it loaded"); angular.module('app.main', []) .run(function(){ alert("it running"); }); console.log(app); app.requires.push('app.main'); 

http://plnkr.co/edit/gN2kkoyqamB4OANXMUjA

Why is this not working? How can i fix this?

+6
source share
1 answer

moduleName.requires undocumented, poorly understood and used only by the Angular injector . The injector, in turn, is called at boot time (via ng-app or angular.bootstrap ) or creates a new injector with angular.injector .

After the application has loaded and the configuration / start phase has finished, new config / run blocks cannot be called. The same goes for moduleName.directive , moduleName.controller and other modular methods, all of which must be called before the application is loaded. Therefore, they are not suitable for defining a module asynchronously.

A recently defined execution unit can be called explicitly by creating an injector (and this means that a new instance of the application is being created):

 var newApp = angular.injector(['app.main']); 

This primary use is testing, and it has a limited application in production - the newly created application and its services cannot communicate with the downloaded application, since the service singletones are different.

There are several solutions for lazy loading in Angular, most fully ocLazyLoad .

+3
source

All Articles