Can I inject a service into a directive in 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;
}
}
});
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;
}
}
}]);
Change your directive definition from app.module
to app.directive
. Apart from that everything looks fine.
Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.
It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.
http://plnkr.co/edit/M8omDEjvPvBtrBHM84Am
You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.
template.html
<div my-directive api-service='ServiceName'></div>
my-directive.directive.coffee
angular.module 'my.module'
.factory 'myDirective', ($injector) ->
directive =
restrict: 'A'
link: (scope, element, attributes) ->
scope.apiService = $injector.get(attributes.apiService)
now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data
For example:
scope.apiService.query((response) ->
scope.data = response
, (errorResponse) ->
console.log "ERROR fetching data for service: #{attributes.apiService}"
console.log errorResponse.data
)
I have found this technique to be very useful when making elements that interact with API endpoints especially.