简体   繁体   中英

Persisting form data when user navigates away from page in Angular

I would like to persist the data entered in a form so that the information entered will still display in the respective fields if the user clicks the back button and then subsequently returns to the form. I've tried using this Stack Overflow answer as a model, but am not having any luck: https://stackoverflow.com/a/16806510/640508

I'm using the Controller As syntax.

Here's my adapted code:

Controller:

angular.module('myApp')
   .controller('ContactFormCtrl', ['formMemory', '$http', function (formMemory, $http) {
var contactForm = this;
contactForm.contact=formMemory;
formMemory.set();
formMemory.get();
// . . . 
}]);

Service:

angular.module('formMemory.fact', [])
    .factory('formMemory', function () {

    var contact = {};

    return {
      get: function () {
        return contact;
      },
      set: function (value) {
        contact = value;
      },
      reset: function () {
        contact = {};
      }
    };

HTML:

<h1><small>ContactInformation</small></h1>
<form name="myForm" novalidate >

   <div class="row">
    <div class="col-sm-4 form-group">
           <label class="control-label" for="first-name">First Name</label>
           <input type="text" id="first-name" name="firstName" ng-model="contactForm.contact.firstName"
           placeholder="First Name" class="form-control">
     </div>
// . . . 

app.js:

angular.module('myApp', [
'formMemory.fact',
  //. . . 
]);

The factory formMemory returns an anonymous object, with 3 functions attached. You aren't using the correct syntax for accessing these functions.

To access the saved data, you would want to set your controller variable to the return value of the get() function, like so:

contactForm.contact = formMemory.get();

and to save the data if you navigate away, you should be passing the contact in as a parameter to the set(value) ; most likely, you would do this in the $routeChangeStart .

$scope.$on('$routeChangeStart', function() {
    //we are leaving the page, so let's save any data we have
    formMemory.set(contactForm.contact);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM