从$ scope获取控制器名称

tom*_*lli 36 angularjs angularjs-scope

有没有办法从AngularJS中的当前$ scope获取控制器名称?

Kev*_*son 30

我不确定这是一个很好的解决方案,但我能够$scope.controllerName使用这种技术注入:

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));
            }
        }]);
}]);
Run Code Online (Sandbox Code Playgroud)

然后

app.controller('SampleCtrl', ['$scope', '$log', function ($scope, $log) {
    $log.log("[" + $scope.controllerName +"] got here");
}]);
Run Code Online (Sandbox Code Playgroud)

  • 感谢分享.代码在角度1.2.x中工作正常,但在1.3中被破坏.演示:http://jsbin.com/muqipe/3/edit?html,console,output在跟踪源代码后,我发现1.3中缺少两个参数,所以它应该是"function(构造函数,本地,以后,缩进)"和"$ delegate(构造函数,locals,稍后,缩进)",供您参考. (11认同)

Tho*_*sen 11

因此,根据Kevin Hakanson的回答和Darkthread的评论,这段代码至少可以使用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);
        };
    }])
}]);
Run Code Online (Sandbox Code Playgroud)


Dav*_*yer 8

这对我也有用.当使用'ngRoute'选择控制器时,我需要一个函数来确定控制器名称是否与给定路径匹配,所以我这样做:

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

然后我可以像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)

我已经在我的配置中添加了路由,例如

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

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

    })
Run Code Online (Sandbox Code Playgroud)


Eng*_*eer 7

不,这是不可能的.如果$scope属于指令怎么办?没有属性可以检索有关作用域所属控制器的信息.


小智 5

在控制器工厂功能中,只需尝试$ attrs服务

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

      var currentControllerName = $attrs["ngController"];

}]);
Run Code Online (Sandbox Code Playgroud)