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.
javascript angularjs
Alex Dn 04 Feb '13 at 13:58
source share