1

I have an app which contains a HTML form, the form uses AngularJS meaning textfields use ng-model to save data into objects within the $scope.

Example:

In HTML:

<input type="text" ng-model="user.firstName">

In the controller:

$scope.user = {}

Now what I am trying to do is auto save user data as they type it within the session storage so if the page gets reloaded/refresh accidentally the data is still there and they don't have to type it all again.

I have tired this:

 <textarea type="text" class="form-control" id="Background" name="Background" ng-model="obj.background" ng-change="autosave()" required></textarea>

In the above code I have ng-change function that runs when the state of the text field changes.

 $scope.autosave = function(){
    $window.sessionStorage.setItem("autosave", $scope.obj);
}

The above code outputs into this:

enter image description here

My Question:

How can I properly make this work so all fields in the form are autosaved and if the page accidentally refreshes the field are populated again with the data. This is the first time I am working with session storage so Im a little confused.

Whats the most efficient way of achieving this.

Skywalker
  • 4,984
  • 16
  • 57
  • 122

2 Answers2

0

You could save it as JSON data instead of doing it directly as an object.

var obj = {};
obj.name = "dooley"
obj.last = "bonheuaa"

window.sessionStorage.setItem("me", JSON.stringify( obj));

After refreshing the page you can do the following to get it back

var me = JSON.parse( window.sessionStorage.getItem("me"))

now me will have the value of the object stored.

Duly Kinsky
  • 996
  • 9
  • 11
  • Thank you for the answer. How would you recommend I populate the textfields with the data from session after page refresh? – Skywalker Jul 21 '16 at 14:43
  • You can have a script that simply retrieves the object from sessionstorage. Then you can do things like: $("#id").val(me.name). Obviously you want to make sure it is there before using it with an if statement or something – Duly Kinsky Jul 21 '16 at 14:48
  • I have tried that but it only works if I remove the ng-model from the text field. Otherwise it doesnt populate the text field. – Skywalker Jul 21 '16 at 15:03
  • I would say Update the model instead of accessing it directly, but idk how that's implemented – Duly Kinsky Jul 21 '16 at 15:10
0

In SessionStorage (https://developer.mozilla.org/fr/docs/Web/API/Window/sessionStorage), you can only put String object.

So, i recommend you to use Stringify on get/set of the sessionStorage. See this post for more information.

Community
  • 1
  • 1
Nico
  • 61
  • 1
  • 7