My angular app have 2 controllers. My problem is that the controllers does not keep the data when the user navigates away from the page.
How can I store the selected data on of my controllers into a data store so it can be used between other controllers?
service
You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)
service definition
app.service('commonService', function ($http) { var info; return { getInfo: getInfo, setInfo: setInfo }; // ................. function getInfo() { return info; } function setInfo(value) { info = value; } });
usage in multiple controllers
app.controller("HomeController", function ($scope, commonService) { $scope.setInfo = function(value){ commonService.setInfo(value); }; }); app.controller("MyController", function ($scope, commonService) { $scope.info = commonService.getInfo(); });
localStorage
You can use the built-in browser local storage and store your data from anywhere
writing
$window.localStorage['my-data'] = 'hello world';
reading
var data = $window.localStorage['my-data'] // ...
If you need to persist data among different users, you should save it somewhere in the server side (db / cache)
function getProfile() { return $http.get(commonService.baseApi + '/api/profile/'); } function updateProfile(data) { var json = angular.toJson(data); return $http.post(commonService.baseApi + '/api/profile/', json); }
EDIT See Jossef Harush's answer where he has written an in-depth response that covers other methods including this one.
I'd recommend using either localStorage or sessionStorage - http://www.w3schools.com/html/html5_webstorage.asp.
HTML local storage provides two objects for storing data on the client:
- window.localStorage - stores data with no expiration date
- window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
This assumes that you don't want to POST/PUT the data to your web service (windows service mention in your question).
If you data is an array or some sort, you can convert it to JSON to store as a string and then when you need it you can parse it back as follows - How do I store an array in localStorage?:
var names = [];
names[0] = prompt("New member name?");
localStorage["names"] = JSON.stringify(names);
//...
var storedNames = JSON.parse(localStorage["names"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With