Javascript 如何将服务注入到包含指令的函数链接?
我试图将服务注入到下面的指令中,该指令用于链接函数而不是控制器Javascript 如何将服务注入到包含指令的函数链接?,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我试图将服务注入到下面的指令中,该指令用于链接函数而不是控制器 (function() { angular .module("myApp") .directive('myDirective',['$scope','myService','myData',function($scope,myService,myData) { return { restrict'AE', replace:'true', templateUrl :'/myApp/directive/my
(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...
}
}
}]);
})();
当我运行这段代码时,会出现异常,比如[$injector:unpr]未知提供程序您有几个语法问题。您的代码应该如下所示:
.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我很确定您应该在链接函数中使用scope而不是$scope,并从Dependenci中删除$scope我如何区分链接函数作用域和默认角度作用域?不确定默认角度作用域的含义,但您可能指的是作用域。$Parents我认为作为调试步骤,我已删除并尝试,但出现了相同的错误:(注意,即使错误将链接到角度文件,如果在角度链接上打开错误,它最终将导致您实际遇到的错误。我需要我的父范围项,因此我正在注入此指令?您不能只使用随附的控制器引用,而不访问父范围吗r链接功能?即链接(范围、元素、属性、控制)