jusopi
jusopi

Reputation: 6813

Using Angular to Inject into non-Angular Objects

Is there a way to provide a non-Angular injection target to the Angular $injector such that Angular constructs like $http, $scope, $location or $q can be injected into it?

//non-angular injection container
var injectionTarget= {
    $http:undefined,
    $scope:undefined
}

//means to inject into target - this is the part in question
var injector = angular.injector();
injector.injectInto( injectionTarget, ["$http", "$scope"]);

I'm having the hardest time finding any info on how to accomplish what I would assume is a very sought-after feature.

Upvotes: 0

Views: 427

Answers (1)

JSager
JSager

Reputation: 1430

I think that probably the easiest way to do this would be to register your objects as services with the module.

var myObject = {} //Defined elsewhere or here as empty

app.service(‘aReferenceName’, function($http){
  myObject.$http = $http;
  return myObject;
});

This would have the double effect of setting the properties you want on your object, and making it accessible from angular as needed. It's also a pretty simple block of code. Note the implication though that as a service it would be a singleton from angular's perspective. If you need to do it as a class with many instances, you'll be wanting a factory.

Upvotes: 1

Related Questions