-1

I want to create cookie, (if it doesn't) exist that would preserve input fields later so that user would not need to type everytime. But I am not sure how it all works? Previously I've done that with local storage, but everytime on submit, I got my local storage overwritten. Could someone clarify steps how should I create cookie and preserve input fields for that user and don't get them rewritten on submit?

user122222
  • 2,179
  • 4
  • 35
  • 78

1 Answers1

2

If you want to use cookies, take a look at Angular's $cookies documentation.

But really, local storage should work fine. You just need to check if the value in the cookie/storage is already set before you set it again. If you don't do that, you'll have the same problem whether you're using cookies or localStorage.

<div ng-app="HelloWorldApp">
    <div ng-controller="HelloWorldController">
        <form>
            <input ng-model="myInput"/>
            <button ng-click="submitForm()">Click Me</button>
          </form>
    </div>
</div>

And the javascript:

angular.module('HelloWorldApp', [])
   .controller('HelloWorldController', function($scope) {
       var savedInput = localStorage.getItem("savedInput");
       if (savedInput){
        $scope.myInput = savedInput;
       }
       $scope.submitForm = function(){
          if (!localStorage.getItem("savedInput") && $scope.myInput){
            localStorage.setItem("savedInput", $scope.myInput);
          }
          alert($scope.myInput);
       };
});
Pharylon
  • 9,796
  • 3
  • 35
  • 59