Nested Dependencies in a Module Launch Method in Angularjs

I am trying to figure out how to work with Angularjs. It looks like a nice structure, but I'm stuck with a little problem with DI ...

How can I inject dependencies in the run method of a module? I mean, I can do this, but it only works if I have service / factory / value with the same name as the name of the run parameter. I am creating a simple application that illustrates what I mean:

var CONFIGURATION = "Configuration"; //I would like to have App.Configuration var LOG_SERVICE = "LogService"; //I would like to have App.Services.LogService var LOGIN_CONTROLLER = "LoginController"; var App = {}; App.Services = {}; App.Controllers = {}; App = angular.extend(App, angular.module("App", []) .run(function ($rootScope, $location, Configuration, LogService) { //How to force LogService to be the logger in params? //not var = logger = LogService :) LogService.log("app run"); })); //App.$inject = [CONFIGURATION, LOG_SERVICE]; /* NOT WORKS */ App.Services.LogService = function (config) { this.log = function (message) { config.hasConsole ? console.log(message) : alert(message); }; }; App.Services.LogService.$inject = [CONFIGURATION]; App.service(LOG_SERVICE, App.Services.LogService); App.Controllers.LoginController = function (config, logger) { logger.log("Controller constructed"); } //The line below, required only because of problem described App.Controllers.LoginController.$inject = [CONFIGURATION, LOG_SERVICE]; App.factory(CONFIGURATION, function () { return { hasConsole: console && console.log }; }); 

Why do I need this, you can ask :) But in my opinion, first of all, in order to have meaningful namespaces for organizing the code. This also minimizes name collisions, and in the latter case, with mini-JS, everything breaks down because it is renamed to shorter names.

+48
javascript angularjs
04 Feb '13 at
source share
1 answer

I think the reason

 App.$inject = [CONFIGURATION, LOG_SERVICE]; 

does not work, because you have 2 more $rootScope and $location parameters that you need to enter in $inject . Therefore, it should be:

 App.$inject = ["$rootScope", "$location", CONFIGURATION, LOG_SERVICE]; 

Another way you can add your service is to use this version:

 app.run(["$rootScope", "$location", CONFIGURATION, LOG_SERVICE, function ($rootScope, $location, Configuration, LogService) { }] ); 
+84
Feb 04 '13 at 14:07
source share



All Articles