Get controller name from $scope

tommaso capelli picture tommaso capelli · Apr 30, 2014 · Viewed 42.2k times · Source

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

Answer

Kevin Hakanson picture Kevin Hakanson · Jun 7, 2014

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");
}]);