Reputation: 705
I am trying to extend the $log provided by AngularJS through .config() and $delegate, so that I can catch all the calls to $log and $broadcast them. This way, other controllers can catch the $log messages and updated independently other parts of the website:
var app = angular.module('testApp', [])
.config(function($provide) {
$provide.decorator('$log', function($delegate, $rootScope, logX) {
return logX($delegate);
});
})
.factory('logX', function() {
return function($delegate, $rootScope) {
return {
log: function() {
console.log('[log] ' + arguments[0]);
$rootScope.$broadcast('XXXlogXXX', arguments[0]);
},
info: function() {
console.info('[info] ' + arguments[0]);
$rootScope.$broadcast('XXXinfoXXX', arguments[0]);
},
error: function() {
console.error('[error] ' + arguments[0]);
$rootScope.$broadcast('XXXerrorXXX', arguments[0]);
},
warn: function() {
console.warn('[warning] ' + arguments[0]);
$rootScope.$broadcast('XXXwarningXXX', arguments[0]);
},
}
};
})
.controller('naCtrl', ['$scope', '$log',
function($scope, $log) {
$scope.init = function() {
$log.info('INIT INVOKED!');
};
}
]);
However, I am getting the following exception (http://jsfiddle.net/rtubio/yu3882nv/2/):
Error: [$injector:cdep] Circular dependency found: $log <- $exceptionHandler <- $rootScope
I have seen a lot of examples at Stackoverflow (like example-1 or example-2), where it is obvious that $rootScope can be used within a factory method. I am pretty sure that it is because I call the .factory method from the .config one, but I still do not understand very well how to break that dependency. Is it possible?
Upvotes: 1
Views: 336
Reputation: 16292
So you can't bring in your logx directly, as the you are in the .config() block.
Instead, bring in the $injector service and get the logx service in the log delegate.
As well, your decorator isn't decorating as much as just replacing the logger. If that was your intention, you can just create your own $log service rather than use a decorator.
var app = angular.module('testApp', [])
.config(function($provide) {
$provide.decorator('$log', function($delegate, $rootScope, $injector) {
var originalLog = $delegate.log;
var originalError = $delegate.error;
. . .
$delegate.log = function() {
var logx = $injector.get('logx');
originalLog.apply(null, arguments);
originalError.apply(null, arguments);
. . .
logx.log(arguments);
logx.error(arguments);
. . .
}
});})
Upvotes: 1