簡體   English   中英

AngularJS:將服務注入指令?

[英]AngularJS: inject service into directive?

我一直在嘗試將D3.js與Angular集成,並遵循本教程: http//www.ng-newsletter.com/posts/d3-on-angular.html

本教程創建了一個包含d3Service的d3模塊,並將其注入到指令中。 我的應用程序結構略有不同,但每當我嘗試注入d3服務時,它在我的指令link函數中顯示為undefined 我可以毫無問題地將d3服務注入我的控制器。 這是我正在做的事情:

app.js

var sentimentApp = angular.module('sentimentApp', [
  'ngRoute',
  'ngSanitize',
  'sentimentAppServices',
  'sentimentAppDirectives',
  'sentimentAppControllers'
]);

services.js ,我有幾個服務,其中一個是d3:

var sentimentAppServices = angular.module('sentimentAppServices', ['ngResource'])
// other services
.factory('d3', [function(){
  var d3;
  d3 = // d3 library code here
  return d3; 
}]);

現在在directives.js

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) {
  // ....
});

將名稱作為字符串傳遞的要點是因為字符串不會受到縮小的影響。 這意味着angular將知道如何在這種情況下注入正確的依賴項:

 ['$compile, d3', function(a, b

a將設置為$compile服務, b將設置為d3服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM