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.

JacobEvelyn
  • 3,901
  • 1
  • 40
  • 51
  • possible duplicate of [Angularjs, passing scope between routes](http://stackoverflow.com/questions/13882077/angularjs-passing-scope-between-routes) – Dan Dascalescu Oct 24 '14 at 11:58

1 Answers1

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?

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 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. – JacobEvelyn Feb 12 '13 at 04:56
  • @ConstableJoe, try turning [$http caching](http://stackoverflow.com/questions/14117653/how-to-cache-an-http-get-service-in-angularjs) on. I should have mentioned that in my answer. – Mark Rajcok Feb 12 '13 at 05:07