0

I have a simple app with a search box and a list of results. The search box has its own controller SearchCtrl, and the list of results has another, DocListCtrl. The SearchCtrl emits an event when the user submits and the DocListCtrl listens, and updates the results. It works fine if a user enters a query and submits- However, my problem is when a user copy/pastes a URL such as "/app/search?q=foo" the search event is broadcast before the DocListCtrl is ready, and therefore the results are not updated.

So in general, is there a way for one controller to declare a dependency on another? Should I have the SearchCtrl persist the data somewhere which the DocListCtrl can look on when it finally loads?

jaredrada
  • 1,130
  • 3
  • 12
  • 25
  • Hi @porfuse. Any reason you're using 2 controllers for this? Couldn't you accomplish with one controller? – vin Aug 07 '13 at 17:58
  • @vin The search ctrl is separate because it will persist in other regions of the app, ex the "detail" view will also have the search form. Also the search ctrl only handles parsing the query and fetching the data from the server, the DocListCtrl handles pagination and a few other things – jaredrada Aug 07 '13 at 18:02
  • Do you even need to broadcast an event? Sounds like the DocListCtrl is a child of the SearchCtrl, can you not get the parent scope and look it up? – Neil Aug 07 '13 at 18:28
  • @Neil how can I declare one controller to be a child of another? – jaredrada Aug 07 '13 at 18:53
  • Quoting Mark who's answered already - By default, child scopes prototypically inherit from the parent scope, so you already have access to the parent controller's properties in the child. – Neil Aug 07 '13 at 19:07

1 Answers1

1

As you already discovered, an app should not be architected in such a way that the order of controller instantiation matters. A better approach is to use a service to manage the search results, which can be injected into both controllers.

Example service: https://stackoverflow.com/a/15390245/215945

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492