Angularjs:从服务中获取服务名称

时间:2014-10-16 09:25:53

标签: angularjs

如何从对象的WITHIN中获取service(或factoryprovidercontrollerdirective ...)的名称?例如

angular.module('app', []).controller('myCtrl', function() {
  // how do I get the name 'myCtrl' here?
})

显而易见的方法是硬编码,但我想避免这种情况

.service('myService', function() {
  this.name = 'myService';
});

我想这是一种方式,但我希望避免它,因为我不想在我的应用程序中声明全局变量

var myCtrlName = 'myCtrl';
angular.module('app', []).controller(myCtrlName, function() {
  console.log(myCtrlName);
});

4 个答案:

答案 0 :(得分:2)

将服务名称定义为变量,以便重用,然后在闭包中包装以避免创建全局变量。

var app = angular.module('app', []);
(function () {
    var serviceName = "myService";
    app.service(serviceName, function () {
        this.name = serviceName;
    });
})();    

答案 1 :(得分:1)

好的,这是怎么做的,但请注意,它非常脏,它使用了来自角度的未记录的东西:D

var app = angular.module('app', []);
app.controller("Ctrl", function($scope, Serv) {

});
app.service("Serv", function() {
  //We're gonna compare functions, the current one and the one registered in the invokeQueue of the app
  var callee= arguments.callee;
  //Loop the invokeQueue 
  _.each(app._invokeQueue, function(inv) {
    //Check if the functions match
    if(inv[2][1] === callee) {
      //Print the name of the current service!
      console.log(inv[2][0]);
    }
  });
});

检查此jsbin以查看它的运行情况: http://jsbin.com/yugogonoya/edit?html,js,console,output

答案 2 :(得分:0)

我认为,它无法获得服务/工厂名称。

如果我们谈论的是控制器名称,则可以通过$routeChangeSuccess活动进行订阅。

$scope.$on('$routeChangeSuccess', function () {
     console.log($route.current.controller);
});

另外,如果我们谈论的是指令。你可以使用这个技巧。

app.directive('directiveOne', function (){
  return {
    controller: 'SomeCtrl',
    scope: true,
    template: '<button ng-click="myFun()">Test A</button>',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.directiveName = 'directiveOne';
    }
  };
});

app.directive('directiveTwo', function (){
  return {
    controller: 'SomeCtrl',
    scope: true,
    template: '<button ng-click="myFun()">Test B</button>',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.directiveName = 'directiveTwo';
    }
  };
});

app.controller('SomeCtrl', function ($scope){
    var ctrl = this;
    $scope.test = function (){
       console.log('Directive name is: ' + ctrl.directiveName);
    };
});

答案 3 :(得分:0)

如果您使用的是ui-router,您可以通过$ state service了解控制器的名称。

$state.current.controller;
相关问题