0

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?

1
  • 1
    You cannot call a directive from a service. Because you cannot inject a directive Commented Jan 8, 2015 at 22:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.