Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get controller name from $scope

Is there a way to get the controller name from the current $scope in AngularJS?

like image 303
tommaso capelli Avatar asked Apr 30 '14 08:04

tommaso capelli


People also ask

What is $scope vs this?

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.

How do you get the $scope in console?

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.

What are the controllers in AngularJS?

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.

What is the difference between $scope and scope?

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.


2 Answers

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"); }]); 
like image 97
Kevin Hakanson Avatar answered Oct 11 '22 12:10

Kevin Hakanson


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);         };     }]) }]); 
like image 24
Thomas Kekeisen Avatar answered Oct 11 '22 12:10

Thomas Kekeisen