Reputation: 2063
So I am basically tranferring data between 2 pages in angular using $route service and not using url params.
I get the data sent to on the second page by the first page but when I refresh the second page data is lost!
How do I solve this,I cant use url params as data will have many text fields and also will be having an array.
I am already using service to pass data but service data doesnt persist after refresh.
I dont want to make database as Its not practical I just want that data to stay on client machine.
Upvotes: 4
Views: 1045
Reputation: 11717
You can use localStorage
to persist the data:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
<script>
angular.module('app', [
'ngStorage'
]).
controller('Ctrl', function(
$scope,
$localStorage
){
$scope.$storage = $localStorage.$default({
x: 42,
y: 1
});
});
</script>
</head>
<body ng-controller="Ctrl">
<button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
</body>
</html>
Upvotes: 1
Reputation: 881
Services are always the best way to store data between controllers. A service persists data through the applications life cycle, therefore we can create a simple one like this:
DataCacheService
angular.module('dataPassingDemo').service('DataCacheService', DataCacheService);
function DataCacheService () {
var self = this,
_cache = {};
self.get = get;
self.set = set;
function get (key) {
if (angular.isDefined(key) && angular.isDefined(_cache[key])) {
return _cache[key];
}
return false;
}
function set (key, value) {
if (angular.isDefined(key)) {
_cache[key] = value;
}
}
Then, given 2 controllers:
Controller 1
angular.module('dataPassingDemo').controller('Controller1', Controller1);
function Controller1 (DataCacheService) {
var vm = this;
vm.setName = setName;
function setName (name) {
DataCacheService.set('name', name);
}
}
Controller 2
angular.module('dataPassingDemo').controller('Controller2', Controller2);
function Controller2 (DataCacheService) {
var vm = this;
vm.name = DataCacheService.get('name');
}
You can see that we are able to pass data between the 2 controllers seamlessly.
You can get more information about services and factories from this article.
Upvotes: 0