How to save object array to localStorage using angular local storage

1.3k views Asked by At

I have this object of array in the controller, how to save this object to a local storage and then access this local storage throughout the app in Angular (Im using ngStorage)

$scope.drivers = [{
            "entity$": "-/sys/daily_journeys",
            "name": "Tom David",
            "journey_count": 90,
            "traveled_distance": "773",
            "total_risk": 0.367,
            "days": 22,
            "id_device": "4564645",
            "avg_risk": "0.0",
            "risk_category": "GREEN"
          }, {
            "name": "James Doc",
            "journey_count": "-",
            "traveled_distance": "-",
            "total_risk": "-",
            "days": "-",
            "id_device": 32423435,
            "avg_risk": "-",
            "risk_category": "NONE"
          }, {
1

There are 1 answers

1
Sajal On

You can use a $cookiestore. set the $scope (key, value) pairs. Inject the shareDataService in the controller.

app.service('shareDataService', ['$cookieStore', function ($cookieStore) {


var _setAppData = function (key, data) { //appId, appName) {
    //var appData = { 'appId': appId, 'appName': appName };
    $cookieStore.put(key, data);
};

var _getAppData = function (key) {
    var appData = $cookieStore.get(key);
    return appData;
};
return {

    setAppData: _setAppData,
    getAppData: _getAppData
};
}]);

Put the service in the main module for the app.