I Have this setting list of background color in my app (white and black), When I choose Black, the background changes to black but after I close the app, it turns back again to white which is the default color. Anyone know how to save setting and load it when the app is re-opened ?
I recommend creating a service (/factory) for managing app settings:
myApp.factory('SettingsFactory', [function() {
var _settingsKey = "appSettings",
defaultSettings = {
bgColor: #fff
};
function _retrieveSettings() {
var settings = localStorage[_settingsKey];
if(settings)
return angular.fromJson(settings);
return defaultSettings;
}
function _saveSettings(settings) {
localStorage[_settingsKey] = angular.toJson(settings);
}
return {
get: _retrieveSettings,
set: _saveSettings,
getBgColor: function() {
return _retrieveSettings().bgColor;
}
setBgColor: function(color) {
var settings = _retrieveSettings();
settings.bgColor = color;
_saveSettings(settings);
}
}
}]);
Then use it in your controller:
myApp.controller('MyCtrl', [$scope, SettingsFactory, function($scope, SettingsFactory) {
$scope.settings = SettingsFactory.get(); // get settings including bgColor
$scope.onBgColorChange = function(color) {
SettingsFactory.setBgColor(color);
}
}]);