$injector.instantiate

in Front-End Web Technologies

Not every class inside Angular application is a service

For example, consider the following class definition

function Contact($http, name, email) {
    this.$http = $http;
    this.name = name;
    this.email = email;
}
 
Contact.prototype.dump = function () {
    console.log(this.name + ", " + this.email);
}
 
Contact.prototype.save = function () {
    //
    //  Work against this.$http
    //
}

Above class represents a single contact and therefore is instantiated multiple times during application execution. This means, that we cannot register it as an Angular factory/service

However, the Contact class has $http dependency. This means that the caller must supply it manually. For example, assuming the caller is a controller which has a reference to $injector it can do the following

angular.module("MyApp").controller("HomeCtrl", function ($injector) {
    var $http = $injector.get("$http");
    var contact = new Contact($http, "Ori", "ori.calvo@gmail.com");
    contact.dump();
});

However, what if the Contact class has many dependencies that must be resolved. Calling $injector.get for every dependency is quite tedious

Fortunately, Angular offers a much elegant solution using $injector.instantiate

angular.module("MyApp").controller("HomeCtrl", function ($injector) {
    var contact = $injector.instantiate(Contact, {
        name: "Ori",
        email: "ori@gmail.com"
    });
 
    contact.dump();
});

Better, much better !!!

Using $injector.instantiate we only need to specify custom parameters (like name and email) and all other dependencies are injected automatically.

Please note that you can call $injector.instantiate multiple times with the same class and every invocation creates and returns a new object. This behavior is different than calling $injector.get which basically returns the same cached object every time you call it

Enjoy,

Contact us
You might also like
Share: