Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get module and controller|service|directive names at runtime

Over at angular-logger, we are trying to enhance $log, but we would like to work in the name of the angular's module and component without changes. To do so we need to get the AngularJS context at runtime, that is, the module name and controller, service or directive names.

app.module("SampleModule").
   controller("ControllerOne", function ($log) {
      $log.debug("I am ready!")
   }).
   controller("ControllerTwo", function ($log) {
      $log.debug("I am ready!")
   });

Default $log output:

> I am ready!
> I am ready!

If we can obtain the module and controller name at runtime, then using the enhanced $log we can get richer output:

> SampleModule.ControllerOne: I am ready!
> SampleModule.ControllerTwo: I am ready!

The best option will be to get it without changes to the controller's code. Perhaps there is way to get some meta info about the entities that received the $log dependency injection?

Any suggestions?

like image 631
pdorgambide Avatar asked May 31 '15 10:05

pdorgambide


1 Answers

There was a similar question that I found on SO, but the solution works only when using controller as syntax.

// a simple route with controller as syntax
$routeProvider.when(
    '/myRoute', 
    { 
        templateUrl: '/myRoute', 
        controller: 'ControllerOne as vm' 
    }
);

// controller
app.controller("ControllerOne", ['$log', function ControllerOne($log) {
    var vm = this;
    $log.log(vm.constructor.name); 
}]);
like image 92
Abhishek Jain Avatar answered Oct 18 '22 09:10

Abhishek Jain