0

I am trying to persit a ng-model as a key and trying to retrive, but its not working when its an object but working when ng-model is string.

<!DOCTYPE html>
<html>

<head>
    <script data-require="angular.js@1.5.7" data- semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>        
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>        
</head>

<body>
    <div ng-app="myApp">
        <input type="text" ng- model="someText.something.firstName" persist="" />
    </div>
</body>

</html>

Plunkr here: http://plnkr.co/edit/QQAxrOjsRzpK6u81J95J?p=preview

Shane
  • 5,517
  • 15
  • 49
  • 79

2 Answers2

1

This question has a great explanation: Storing Objects in HTML5 localStorage

The short answer is that you will need to stringify any objects you want to store in localStorage, but be aware that there are some caveats to stringifying JS objects.

scope.$watch(model, function (value) {
  localStorage[key] = JSON.stringify(value);
});
Community
  • 1
  • 1
Pop-A-Stash
  • 6,572
  • 5
  • 28
  • 54
0

Joel is correct in that you must stringify objects, you also need to keep in mind that you can't have any circular references and that there IS a limit on how much stuff you can dump into localStorage. Due to that limit it's also a good idea to have a system in place to keep track of which items should be pushed out of cache and to actually invalidate them.

Sandwich
  • 61
  • 5