Reputation: 4217
What is the proper way to establish a self-referential pattern in Angular using factories? For example, if I have a parent-child relationship of the same type of object:
angular.module('app.factories')
.factory('PersonFactory', function(PersonFactory) {
function Person(name) {
this.name = name;
this.mom = new PersonFactory('Frank');
this.dad = new PersonFactory('Sue');
}
Person.prototype.getMom = function() {
return this.mom;
};
Person.prototype.getDad = function() {
return this.dad;
};
return Person;
});
This (obviously) is returning a circular dependency error.
Upvotes: 0
Views: 175
Reputation: 54791
You can't create an object that creates itself in the constructor. Otherwise you get an infinite loop. The object should either take the parents as constructor parameters, or you add setters.
function Person(name, father, mother) {
this.name = name;
this.father = father;
this.mother = mother;
}
var child = new Person("Timmy", new Person("Frank"), new Person("Sue");
You can use Person
inside the factory declaration directly. It doesn't have to be injected.
function Person(name, parent) {
this.name = name;
if(!parent) {
this.mom = new Person("Sue", true);
}
}
var child = new Person("Timmy");
Upvotes: 3