我可以将服务注入 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屋!
查看全文