My current challenge involves developing an application that is predominantly angular-based, but also incorporates some non-angular code. I have structured my code into modules, including various factories. One of these factories is specifically dedicated to logging and is utilized across different modules.
The issue arises when I need to access this logging factory from areas of the code that are not within the angular framework and therefore cannot leverage Angular's dependency injection mechanism.
/* Angular app */
var app = angular.module('myApp', []);
app.factory('logger', function(){
return {
infos : [],
logInfo : function(msg) { this.infos.push(msg); }
};
});
app.controller('MyCtrl',['logger', function(logger){
...
logger.logInfo("I can easily use the injected logger here");
...
}]);
/* Remaining parts of the app */
someLib.someMethod(function(){
...
// var logger = angular.getFactory('logger') ?
logger.logInfo("How do I access the logger from this non-angular section?");
...
});
I have managed to find a workaround for this issue, although it is not entirely ideal or secure:
// Global declaration of the logger
var logger = {
infos : [],
logInfo : function(msg) { this.infos.push(msg); }
};
// Still encapsulating it within a factory (even though its purpose is diminished now)
app.factory('logger', function(){
return logger;
});
/* Remaining parts of the app */
someLib.someMethod(function(){
...
logger.logInfo("Now that logger is global, it can be accessed from anywhere!");
...
});
Thus, the question remains: Is there a method to inject dependencies in sections of the code that are outside of Angular?