0

I have two objects, a House and a Tenant, both described and constructed in factory methods. For the purposes of the app, each Tenant may have more than one house and each House may have more than one tenant. Thus, each object needs to keep an array of the other and be able to perform functions on the other. For instance, when a User is looking at his/her overview, he can see an icon of all of his/her houses to click on to be taken into the "House Page" for that particular house. In the "House Page" the house must know who are the tenants so that bills can be split between all of the tenants and chores can be assigned to tenants.

My problem is that when creating factory methods, I run into circular dependance injection and Angular JS doesn't seem to like that. I can't seem to think of a solution. Any suggestions?

  • Welcome to Stack Overflow! If my answer solved your problem, mark it as accepted by clicking the accept checkmark to the left of the question (this will also earn you some reputation). Let me know if you need some more information/help. If you do, include some more details in your post. A generalized bit of code recreating the problem and a demo on something like jsbin.com makes for a great post. – m59 Sep 08 '14 at 18:09
  • possible duplicate of [Problems with circular dependency and OOP in AngularJS](http://stackoverflow.com/questions/19344214/problems-with-circular-dependency-and-oop-in-angularjs) – Blackhole Sep 08 '14 at 18:22
  • @Blackhole Oops, I see we answered this similarly! I forgot to check for duplicates first. My apologies!! – m59 Sep 08 '14 at 21:20
  • @m59 No problem, two answers are better than one :) . Feel free to edit my own answer if you can improve it! – Blackhole Sep 08 '14 at 22:00

1 Answers1

1

This is a common problem which notifies you that you need a third service. You should factor out the shared logic into a third service so that they both need the third service rather than needing one another.

Misko Hevery, the author of Angular, wrote an article about this problem.

To summarize, he explains:

One of the two objects is hiding another object C. Either A contains C or B contains C. To find out which one it is, list all of the methods in your class A used by class A, and all the methods in your class B used by class A. The shorter of the two lists is your hidden Class C.

m59
  • 43,214
  • 14
  • 119
  • 136
  • thanks, I had read that post by Misko before posting here. I just struggled to apply his A's, B's, C's analogy to my application. Can you give an example of what this third service could be? –  Sep 08 '14 at 21:17
  • @JoãoRitter It doesn't really make any sense for me to make an example rather than you either show your code or a more generalized example (preferable) as I suggested in my comment on your question. – m59 Sep 08 '14 at 21:19