Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  19] [ 1]  / answers: 1 / hits: 40132  / 9 Years ago, sat, july 25, 2015, 12:00:00

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?


More From » angularjs

 Answers
76

Option 1 - custom 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();

});





Option 2 - html5 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']
// ...







Option 3 - via web server api



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);
}

[#65681] Thursday, July 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;