How to pass a simple array data in ngStorage,$localstorage?

1.9k Views Asked by At

So lets say I want to define an var array=['a','b','c']

How do I pass this array into localStorage ?

Should I just simply write $localStorage.data = array;?

And also how to check if that array $localStorage.data is not empty and not undefined?

2

There are 2 best solutions below

2
On BEST ANSWER

How do I pass this array into localStorage ? Should I just simply write $localStorage.data = array;?

Yes, you simply put it like this:

$localStorage.data = array

And also how to check if that array $localStorage.data is not empty and not undefined?

Check it like simple variable

if($localStorage.data){
    console.log('empty');
} else{
    console.log('Data', $localStorage.data);
}

ngStorage

Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.

3
On

You can simply store in localstorage as:

localStorage.setItem("data", JSON.stringify(array));

and later retrieve it as

$scope.data= JSON.parse(localStorage.getItem("data"));

You can check $scope.data by doing

console.log($scope.data);