Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service functions outside Angularjs scope

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.

like image 709
giulio Avatar asked Jan 23 '14 15:01

giulio


People also ask

Can we use $scope in service?

Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service).

What is scope in AngularJS explain the services in AngularJS?

The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

What is the difference between $scope and scope in angular?

In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.


1 Answers

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.

like image 187
calebboyd Avatar answered Sep 26 '22 17:09

calebboyd