I'd like some advice on how to share some data between two or more controllers in AngularJS.
For now I'm just dealing with two controllers, but in the future I will have more controllers that will also want to use this same data. Right now I have a navigation-controller
which is controlling the side navigation
and the header
. And for ease of understanding, let's say the second controller is called content-controller
which is responsible for dealing with all the content.
I want to dynamically load the content based on whatever the user searches for and the search bar is in the side navigation, so this searchTerm
needs to be accessible by both controllers. In the future, I would also implement some other features which would probably need to access this searchTerm as well.
In terms of the HTML structure, the content-controller
is inside the navigation-controller
.
My first thought was to make searchTerm
globally available by sticking it in $rootScope
, but I'm unsure if this is an efficient/secure way to do it.
My second thought was to take the searching aspects and put them into a service
. Inside this service I would put functions which would speak to the API in order to get the necessary data. This would mean on the search bar, I can make the submit search
button access the service
and run something like FooService.update(searchTerm)
.
What do you think the best way to deal with this scenario is?