我可以在AngularJS的指令中注入服务吗? [英] Can I inject a service into a directive in AngularJS?
本文介绍了我可以在AngularJS的指令中注入服务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将服务注入如下指令:
I am trying to inject a service into a directive like below:
var app = angular.module('app',[]);
app.factory('myData', function(){
return {
name : "myName"
}
});
app.directive('changeIt',function($compile, myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
});
但是这将返回错误Unknown provider: myDataProvider
.有人可以调查一下代码,并告诉我是否做错了什么?
But this is returning me an error Unknown provider: myDataProvider
. Could someone please look into the code and tell me if I am doing something wrong?
推荐答案
您可以对指令进行注入,看起来就像在其他地方一样.
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
这篇关于我可以在AngularJS的指令中注入服务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文