简体   繁体   中英

AngularJS: Injecting services and factories into a non-AngularJS function

I'd like to be able to execute custom external scripts during runtime and give them access to my AngularJS custom services and factories.

The loaded scripts shouldn't be controllers, as I have no interest in linking them to any views.

It should look like that:

1) Load an external script during runtime

2) Inject into that function custom AngularJS services and factories, then execute it.

Is it possible to inject that way?

To answer the question as you asked it - yes, you could do something like this.

You could use the injector to get a service instance:

angular.injector(["Your.Service.Module"]).get("FooSvc");

Keep in mind that if your service has other dependencies, then you would need to specify all of them. For example, if your service needs $timeout :

angular.module("fooModule", []).factory("FooSvc", function($timeout){
  ...
}

then you would need to inject it like so:

var fooSvcInstance = angular.injector(["fooModule", "ng"]).get("FooSvc");

Also, note that the instance of the service will be different than what will be injected into your app.

Plunker

You should re-evaluate why you need to do this.

EDIT

To get the same instance of the service as what the app gets you would need to get the same instance of the injector. To do that, you would need to object the injector from a DOM element in your Angular's app. For example, let's say that <body> is in your app:

// make sure that body has loaded (for example, in window.onload)
var injectorInstance = angular.element(document.body).injector();
var fooSvcInstance = injectorInstance.get("FooSvc");

Updated Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM