我想了解如何使用Angularjs。它看起來像不錯的框架,但我堅持與DI的一個小問題...在Angularjs模塊的「運行」方法中注入依賴關係
我如何注入依賴在模塊的「運行」方法?我的意思是我能夠做到這一點,但它只有在我的service/factory/value與「run」參數名稱相同的情況下才有效。 我建立一個簡單的應用程序就說明我的意思:
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 }; });
爲什麼我需要它可能你問:)不過在我看來,首先關閉所有有有意義的命名空間來組織代碼。它還可以最大限度地減少名稱衝突,並且在最後減少JS的時候,事情會崩潰,因爲它重命名爲更短的名稱。
有一個在run方法小錯字,第二支架是沒有必要的。 –