15

I'm new to AngularJS and am trying to build myself a simple little app. I have JSON data for the app being fetched with $resource, and this data should be the same across multiple views/routes. However, when I go to a new route, the JSON data (stored as $scope.data) is no longer available to the new view. What can I do to pass this data to the new view and not require another fetch? (The tutorial phone-catalog app re-fetches this data every time from what I can tell.)

From what I understand, $rootScope can do this but it seems to be generally frowned upon. I apologize if this doesn't make much sense; I'm very much diving in the deep end here.

1

1 Answer 1

17

Use a service to store the data. Inject that service into each controller that needs access to this data. Each time a controller is created and executes (because you switch to another view/route), it can ask the service for the data. If the service doesn't yet have the data, it can make a request to the server and return a promise to the controller (see below for how to do that). If the service has the data, it can return it to the controller immediately.

See also Processing $http response in service

Note that services are singletons, unlike controllers.

Another variation: when the service is created, it can go fetch the data itself, and then store it for later use. Controllers can than $watch properties or functions on the service. For an example of this approach see How do I store a current user context in Angular?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the thorough response! Unfortunately, I still can't seem to get it to work (I'm trying the first method, which seems more natural to me). I have $routeProvider defining two routes, for now each mapping to the same controller. The controller calls service.async().then(...) and the service's async method returns the promise defined by http.get('/data.json'). And each time I navigate within the app to a new route, a new HTTP request to data.json is made. Any thoughts would be greatly appreciated.
@ConstableJoe, try turning $http caching on. I should have mentioned that in my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.