3

I'm wondering what's the best (per Angular way) of passing data between views that display on particular route and I would like to avoid passing data via URL as there can be a lot of it or would require some sort of conversion to strings etc. All in all not a good idea.

An example to understand this:

I have a create new content view which displays with empty fields and users are free to enter all the data they want. But in some cases I would like some of these fields to be pre-populated with data based on what users did on previous view.

Each view has its own controller. Would communicating via services maybe still work? Is there any other way and simpler so we don't have to take care of data lifetime (i.e. if we talk via service we have to manually discard data after being read).

I'm wondering what's the Angular-suggested way of doing this?

Robert Koritnik
  • 97,460
  • 50
  • 267
  • 388
  • Possible duplicate of [AngularJS - Passing data between pages](http://stackoverflow.com/questions/22408790/angularjs-passing-data-between-pages) – T J Dec 12 '15 at 14:35

1 Answers1

2

Yep, service or factory would be fine for this case. You could also store that previously entered data in local storage for example using that service. Basically it's better way for improvements in future.

As a simpler way, you can simply use $rootScope. It's available in all your controllers it you wish so.

Just need to inject it into controller or in the app itself.

app.controller('myCtrl', function($rootScope){
    $rootScope.myStoredValues = {...};
});

or

app.run(function($rootScope){
    $rootScope.root = $rootScope; 
    $rootScope.myStoredValues = {...};
    // this way you don't need to inject it into controller, 
    // it will be available there via $scope.root.myStoredValues
});
gorpacrate
  • 4,149
  • 3
  • 18
  • 18