angularjslocal-storageng-storage

Save array in ng-storage AngularJS


how save and display array in angular?

example:

$scope.save = function () {
    var myOby= [
    { name: 'A', address: '1' },
    { name: 'B', address: '2' },
    { name: 'C', address: '3' },
    { name: 'D', address: '4' }
    ];
    //save
}
$scope.load = function() {
    //show
}

Any solution?


Solution

  • localStorage supports arrays, and any other valid JSON (objects, strings, numbers), and not for example functions.

    Here is a plunkr demonstrating this

    The angular code:

    var app = angular.module('myApp', ['ngStorage']);
    
    app.controller('myCtrl', function($scope, $localStorage) {
      $scope.text = "Hello!";
      $scope.save = function () {
        var myOby= [
        { name: 'A', address: '1' },
        { name: 'B', address: '2' },
        { name: 'C', address: '3' },
        { name: 'D', address: '4' }
        ];
        //save
        $localStorage.myKey =  myOby;
    }
    $scope.load = function() {
        //show
        $scope.restored_data = $localStorage.myKey;
    }
    });
    

    As mentioned in the comments above, this information is readily available in the documentation: Documentation