Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve data through AngularJS routing?

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.

like image 674
JacobEvelyn Avatar asked Feb 12 '13 03:02

JacobEvelyn


People also ask

Which ability of angular is achieved through routing?

So, when we say navigation in an Angular application, it simply means navigating between those components. It can be achieved by implementing routing.

What is UI routing in AngularJS?

Angular-UI-Router is an AngularJS module used to create routes for AngularJS applications. Routes are an important part of Single-Page-Applications (SPAs) as well as regular applications and Angular-UI-Router provides easy creation and usage of routes in AngularJS.


1 Answers

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?

like image 158
Mark Rajcok Avatar answered Oct 09 '22 02:10

Mark Rajcok