7

I have created a service in angularJS that uses btford.socket-io module to interact with the server. Since in the service I have implemented some API that I use inside angular at the moment, but for later extension of the application I also need to give access to these API outside angular scope. So that in future one could just call the function without having the need to create controller and other stuff.

At the moment I did this for a controller

var myController = angular.element($('body')).scope().myController;

by saving the whole controller inside a scope variable. I was wondering if it would be possible to do the same with a service.

1 Answer 1

12

How about:

angular.element(document.body).injector().get('MyService');

Typically not good practice. But sometimes its needed.

Note: document.body is the element Your angular application is mounted to

Another thing you might consider is 'closing' external api with angular via a factory.

  • eg. return your global or namespaced class or api from an angular factory.

This is essentially what angular does for you. But instead of creating the reference inside angular first and having to extract it, you'd create it outside, and register it with DI as a factory or value.

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

1 Comment

It works :) I know that this is bad, because I'm working outside the angular scope. Since I am creating several directives using angularjs as framework and in the same time I also would like to use the service for external developer API I think there are no alternatives. Maybe rewrite the API separated from angularjs would be a possibility, but this would affect the architecture design.

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.