Javascript AngularJS:将服务注入指令?
我一直在尝试将D3.js与Angular集成,并遵循本教程: 本教程创建了一个d3模块,该模块包含Javascript AngularJS:将服务注入指令?,javascript,angularjs,dependency-injection,d3.js,Javascript,Angularjs,Dependency Injection,D3.js,我一直在尝试将D3.js与Angular集成,并遵循本教程: 本教程创建了一个d3模块,该模块包含d3Service,并被注入到指令中。我的应用程序的结构稍有不同,但每当我尝试注入d3服务时,它就会在我的指令链接函数中显示为未定义。我可以将d3服务注入我的控制器而不会出现问题。以下是我正在做的: app.js: var sentimentApp = angular.module('sentimentApp', [ 'ngRoute', 'ngSanitize', 'sentimen
d3Service
,并被注入到指令中。我的应用程序的结构稍有不同,但每当我尝试注入d3服务时,它就会在我的指令链接函数中显示为未定义。我可以将d3服务注入我的控制器而不会出现问题。以下是我正在做的:
app.js
:
var sentimentApp = angular.module('sentimentApp', [
'ngRoute',
'ngSanitize',
'sentimentAppServices',
'sentimentAppDirectives',
'sentimentAppControllers'
]);
var sentimentAppDirectives = angular.module('sentimentAppDirectives', ['sentimentAppServices']);
sentimentAppDirectives.directive('lsPieChart', ['d3', function($compile, d3){
return {
// scope & template
link: function($scope, elem, attr, ctrl) {
console.log(d3); // undefined
}
}
在services.js
中,我有几个服务,其中一个是d3:
var sentimentAppServices = angular.module('sentimentAppServices', ['ngResource'])
// other services
.factory('d3', [function(){
var d3;
d3 = // d3 library code here
return d3;
}]);
现在在directions.js
中:
var sentimentApp = angular.module('sentimentApp', [
'ngRoute',
'ngSanitize',
'sentimentAppServices',
'sentimentAppDirectives',
'sentimentAppControllers'
]);
var sentimentAppDirectives = angular.module('sentimentAppDirectives', ['sentimentAppServices']);
sentimentAppDirectives.directive('lsPieChart', ['d3', function($compile, d3){
return {
// scope & template
link: function($scope, elem, attr, ctrl) {
console.log(d3); // undefined
}
}
有什么建议吗?谢谢。问题在于,您暗示的依赖项与您实际传递的不匹配:
['$compile, d3', function($compile, d3
因此,您所做的是将d3
服务作为变量$compile
传递,而不是作为变量d3
传递任何内容
这可能会帮助你理解这是为了什么。在非精简代码中,您可以将该数组包装器一起取出,如下所示:
app.directive('directiveName', function($compile, d3) {
// ....
});
['$compile, d3', function(a, b
将名称作为字符串传递的意义在于字符串不会受到缩小的影响。这意味着angular将知道在这种情况下如何注入正确的依赖项:
app.directive('directiveName', function($compile, d3) {
// ....
});
['$compile, d3', function(a, b
a
将被设置为$compile
服务,b
将被设置为d3
服务。请注意,如果您使用ngmin实用程序(如果在缩小之前使用),您并不总是需要它,因为它是自动完成的。这可以简化维护,因为您可能会意外遇到本主题中描述的类似问题。