Get controller name from $scope

守給你的承諾、 提交于 2020-01-19 07:11:28

问题


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


回答1:


No, it is not possible. What if $scope belongs to directive? There is no property that can retrieve information about the controller the scope belongs to.




回答2:


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



回答3:


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



回答4:


This also works for me. I needed a function to determine if the controller name matched a given route, when using 'ngRoute' to select a controller, so I did this:

app.controller('navigation', function($scope, $route) {
  $scope.tab = function(route) {
    return $route.current && route === $route.current.controller;
  }
}

Then I can use it like this:

<div ng-controller="navigation" class="container">
    <ul class="nav nav-pills" role="tablist">
        <li ng-class="{active:tab('home')}"><a href='#/'>home</a></li>
        <li ng-class="{active:tab('dashboard')}"><a href='#/dashboard'>dashboard</a></li>
    </ul>
</div>

Where I have already added routes to my config, e.g. something like

angular.module('app', [ 'ngRoute' ]).config(
    function($routeProvider) {

        $routeProvider.otherwise('/');
        $routeProvider.when('/', {
            templateUrl : 'home.html',
            controller : 'home'
        }).when('/dashboard', {
            templateUrl : 'dashboard.html',
            controller : 'dashboard'
        });

    })



回答5:


In controller factory function, just try $attrs service

app.controller("MyController", ["$attrs", function($attrs){

      var currentControllerName = $attrs["ngController"];

}]);



回答6:


just this.constructor.name anywhere that the scope of that class is available once instantiated.




回答7:


The question is getting a little old but it might still be helpful for some of you... I found a way to get controller name but it only works with a Controller as syntax. I can now do my logging more easily without having to manually re-write my controller name every single time. Here is an example:

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

// controller
app.controller("ContactController", ["$log", function ContactController($log) {
    var vm = this;
    $log.log(vm.constructor.name); 
}]);

If you want to do it from the DOM (from javascript legacy code), you could also do it this way:

// scope element via the DOM
var scope = angular.element($(element)).scope();    
console.log(scope.this.vm.constructor.name);

// controller element via the DOM
var controller = angular.element($(element)).controller();    
console.log(controller.constructor.name);


Edit
Also tried the suggestion of Dave Syer it actually works on $scope as for example:

app.controller("ContactController", ['$route', function ContactController($route) {
  console.log($route.current.controller);
}]);



回答8:


It is possible to get scope of directive as well as scope of controller using jQuery.

 window.top.$('[ng-controller="mainCtrl"]').scope(); // get scope of controller

 window.top.$('[epubby-page-view]').scope(); // get scope of directive

We can execute a method or update any variable from anywhere using this scope fetching methods.

For example: consider we want to execute a method from mainCtrl controller, we just need to give a direct call to method as follows:

var myData = window.top.$('[ng-controller="mainCtrl"]').scope().getData();



回答9:


If you are debugging from the console, this I found useful:

  1. Select the element in the UI whose controller you are searching for in Chrome dev tools
  2. Input in the console: angular.element($0).controller().__proto__

It will get you the prototype of the controller, inside its constructor, there is FunctionLocationthat corresponds to a file. If you make your controllers one per file like you should, you found your controller there. It's even better if you name your files as a controller, I don't see why you would not.

I know it's not exactly what you asked for but I find it helpful and extremely easy to use right from the dev tools.



来源:https://stackoverflow.com/questions/23382734/get-controller-name-from-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!