RaV
RaV

Reputation: 1048

Restoring form from LocalStorage when page refresh

<div ng-repeat="filterSection in filterSections">
    <h4>{{ filterSection.title }}</h4>
    <div class="checkbox" ng-click="loaderStart()" ng-if="filterSection.control == 'checkbox'" ng-repeat="option in filterSection.options">
        <label>
            <input type="checkbox" ng-model="searchParameters[filterSection.key][option.key]" value="{{ option.key }}" checked><span></span> {{ option.value }}
        </label>
    </div>
</div>

I can access it with $scope.searchParameters.

I can store it using localStorage.setItem('search', JSON.stringify(cleanedParameters));

I can access store with JSON.parse(localStorage.getItem("search"));

But I have no idea how could I restore it when page refresh. Is there some function or example of directive which I could use? I couldn't really find anything similar to my problem.

Upvotes: 1

Views: 366

Answers (4)

RaV
RaV

Reputation: 1048

I found out I can just inject this straight back into $scope without much effort. This solution works just fine: $scope.searchParameters=JSON.parse(localStorage.getItem("search"));

I was trying to parse whole thing by myself, but it was not worth effort :)

With $scope.$watch('searchParameters', function (newValue, oldValue) I check if element has changed and I update it in LocalStorage.

Upvotes: 0

Ozrix
Ozrix

Reputation: 3515

I'm using ngStorage (to abstract away all the JSON parse stuff) - http://ngmodules.org/modules/ngStorage

Then anywhere (in my controllers, directives, services), I inject the $localStorage provider, and load the storage into the $scope:

app.controller("FooCtrl", ["$scope", "$localStorage", function($scope, $localStorage){

   $scope.storageStuff = $localStorage.somethingSavedInStorage;

}]);

EDIT: http://jsfiddle.net/Lvc0u55v/2997/

Upvotes: 0

Sampath
Sampath

Reputation: 65880

You can try as shown below.Just create an array and push the values into that.Then you can access that array values as you wish through a loop.

var a = [];
a.push(JSON.parse(localStorage.getItem('search')));

Upvotes: 1

user6250958
user6250958

Reputation: 31

You can use LocalStorageService module of angularJs.

for more detail please check this link https://www.npmjs.com/package/angular-local-storage

Upvotes: 2

Related Questions