Reputation: 826
I am trying to call a directive from a service. I have implemented everything but my service scope is coming up empty. Normaly my functions are calling a directive from a controller. But these functions are now needed across multiple controllers so I want to put them in a service. Problem is my service cant see the functions in the directive even after doing dependency injection of the directive into the service.
export interface MyServiceScope extends IScope, directives.MyPanelScope, directives.MyPanelMenuScope {
// a bunch of properties that are not visible in the service scope, only the controller
}
// constructor here, controller does not initialize directives here just in interface and it works fine.
public serviceFunc() {
this.scope.panel.directiveFunc({ // directiveFunc undefined in service, but not in controller
template: "some/html/template",
data: {
item: data
}
});
}
So what do I do about getting the service to see the directive and call its functions?
Upvotes: 0
Views: 814
Reputation: 1673
You cannot inject a directive into a service n Angular. Actually you cannot inject a directive anywhere. Directives are supposed to be a set of functions that strictly relate to specific DOM elements, and it is usually bad practice to use them to share code between different parts of the app. That purpose can be fulfilled by services.
If you find yourself in the situation where a service needs to call some function from a directive, I suggest that you review your code structure. I don't know the specifics of your case, but you could take the "shared" logic out of your directive into a service, inject that service into the directive and call it from there. In this way the logic called by the directive will be available to be injected to other parts of the application as well.
Upvotes: 2