Although AngularJS itself does not provide out of the box prototypical inheritance, here are at least a couple of ways to go about doing this:
- The second way, which I FAR prefer is applying standard OO patterns to Javascript and implementing them in AngularJS. In this case, what *I* would do is create a 'shell' AngularJS service. Inside it create an object FACTORY to return the proper object instance, which is within a parallel JS inheritance hierarchy. This way you will have the best of both worlds, where your service will act as a Singleton AND maintain a dictionary of objects it manufactures if it needs to. NOTE: The factory itself can be a separate service that can be injected into your service which is even better. Below is some pseudocode so it is syntactically incorrect. Note, the object hierarchy can be data returned to the controller to update its scope attributes OR it can be data returned to the service for other purposes. I have called 'baseMethod()' to show both cases. Hope this helps.
{//object prototype hierarchy:
BaseObject = function () {
}
BaseObject.prototype.baseMethod = function() {...}
ChildObject1 = function() { ..}
ChildObject1.prototype=Object.create(BaseObject.prototype);
ChildObject1.prototype.baseMethod = function() {...}
...
ChildObjectn = function() { ..}
ChildObjectn.prototype=Object.create(BaseObject.prototype);
ChildObjectn.prototype.baseMethod = function() {...}
}
angularJSController('Controller', injected = "FactoryService") {
object = FactoryService.create('condition parameters');
object.baseMethod(); //if this a controller type call
}
angularJSService('FactoryService') {
var object = null;
var ObjectDict = [];
var create = function ('condition parameters') {
case 0: object = new ChildObject0;
case 1: object = new ChildObject1;
....
case n: object = new ChildObjectn;
default: new ChildObject;
objectDict.push(object); //manage objects
object.baseMethod(); //if this a service type call
return object;
}
return this;