Is there a way to get the controller name from the current $scope in AngularJS?
When the controller constructor function is called, this is the controller. When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on.
To examine the scope in the debugger: Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted. The debugger allows you to access the currently selected element in the console as $0 variable.
AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.
In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.
I'm not sure this is a good solution, but I was able to inject $scope.controllerName
using this technique:
app.config(['$provide', function ($provide) { $provide.decorator('$controller', [ '$delegate', function ($delegate) { return function(constructor, locals) { if (typeof constructor == "string") { locals.$scope.controllerName = constructor; } return $delegate.apply(this, [].slice.call(arguments)); } }]); }]);
Then
app.controller('SampleCtrl', ['$scope', '$log', function ($scope, $log) { $log.log("[" + $scope.controllerName +"] got here"); }]);
So, based on the answer from Kevin Hakanson and the comment from Darkthread, this code works with at least 1.3.15:dev
app.config(['$provide', function ($provide) { $provide.decorator('$controller', ['$delegate', function ($delegate) { return function (constructor, locals, later, indent) { if (typeof constructor === 'string' && !locals.$scope.controllerName) { locals.$scope.controllerName = constructor; } return $delegate(constructor, locals, later, indent); }; }]) }]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With