0

我正在嘗試將服務注入下面的使用鏈接函數而不是控制器的指令。如何注入鏈接函數包含指令的服務?

(function() { 
angular 
.module("myApp") 
.directive('myDirective',['$scope','myService','myData',function($scope,myService,myData) { 
return { 
    restrict'AE', 
    replace:'true', 
    templateUrl :'/myApp/directive/my-directive', 
    scope: { 
     userId: "@" 
     } 
    }, 
    link:function(scope,elem,attr) 
     { 
     //Code for link function goes here ... 
      scope.myUsersArray []; 
      scope.getUserDetails = function() 
       { 
       //code for getUserdetails goes here... 
       } 

     } 
    }]); 
    })(); 

當我運行這段代碼,我得到像例外[$注射器:unpr]未知提供商< _ $範圍錯誤。如果我刪除注入的服務,我沒有收到任何錯誤。錯誤拋出的angular.js文件,所以我沒有任何線索來解決它:(

+3

我很確定你應該在你的鏈接函數中使用作用域而不是$ scope,並從依賴中刪除$ scope – juvian

+0

我如何區分鏈接功能範圍和默認的角度範圍? – JsLearner

+0

不確定你的意思是默認的角度範圍,但你ar $ parent – juvian

回答

0

你有幾個語法問題,你的代碼應該是這樣的:

.directive('myDirective', ['$scope', 'myService', 'myData', function($scope, myService, myData) { 
    return { 
     restrict: 'AE', 
     replace: 'true', 
     templateUrl: '/myApp/directive/my-directive', 
     scope: { 
     userId: "@" 
     }, 
     link: function(scope, elem, attr) { 
     //Code for link function goes here ... 
     scope.myUsersArray = []; 
     scope.getUserDetails = function() { 
      //code for getUserdetails goes here... 
     }; 
     } 
    }; 
    }]); 

您可能會遇到問題多爲它不明顯爲什麼你注入$ scope,myService和myData

+0

我需要我的父作用域項目,所以我正在注入此指令? – JsLearner

+0

而不是訪問父範圍,你不能只使用你的控制器的引用與你的鏈接功能?即鏈接(範圍,元素,attrs,ctrl) – jbrown

相關問題