2014-10-16 6 views
2

내에서 서비스 이름을 얻을 service (또는 factory, provider, controller, directive ...) 오브젝트 내에서? 예AngularJS와 : 내가 이름을 얻을 수있는 방법 서비스

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); 
}); 
+0

당신은 왜 이것을 필요로합니까? 코드의 이름에 의존하는 순간 문제가 발생합니다. – Yoshi

+0

@ Yoshi 중재자 서비스로 콜백을 등록하는 데 사용하고 싶습니다. 서비스의 이름을 .init의 중재자에게 전달하므로 중재자는 각 서비스에 대한 ID를 갖습니다. 조정자 (mediator)는 이름에 의존하는'$ routeProvider.when ('/', {templateUrl : 'views/main.html', 컨트롤러 : 'myCtrl', ...})'과 같은 엔드 포인트를 연결하며, (참으로 축하받은) Angular의 패턴. 또 다른 제안이 있니? – poshest

+0

각 이름의 사용은 항상 한 번에 해당 요소가 특정 이름으로 등록되었다는 사실에 의존합니다. 그것은 결코 추측되거나 유사하지 않으며, 항상 setter/getter 관계입니다. 당신이하려고하는 것이 같은 개념인지는 확실치 않습니다. 또한 귀하의 질문에 관해서는 귀하의 의견에서 이것은 [X-Y 문제] (http://mywiki.wooledge.org/XyProblem)처럼 보입니다. – Yoshi

답변

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); 
    }; 
}); 
+0

지시어 트릭을 사용하면 'angular.module ('app ', [])과 같은 방식으로 서비스 이름을 항상 하드 코딩 할 수 있습니다. service ('myService ', function() {this.name ='myService ' })'. 그게 내가 피하려고하는 다른 방법이다. (그냥 내 질문에 덧붙였다.) – poshest

0

ui-router를 사용하는 경우 $ state 서비스를 통해 컨트롤러의 이름을 알 수 있습니다.

$state.current.controller; 
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

+0

너무 답답함을 받아들이 기가 너무 어둡지 만 독창성은 +1한다. 나는 너를 내 팀에 보내고 싶다. :) – poshest

2

서비스 이름을 변수로 정의하여 재사용 할 수 있도록 한 다음 클로저를 사용하여 전역 변수가 작성되지 않도록하십시오.

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