繁体   English   中英

当用户离开Angular页面时保留表单数据

[英]Persisting form data when user navigates away from page in Angular

我想保留在表单中输入的数据,这样,如果用户单击“后退”按钮然后随后返回到表单,则输入的信息仍将显示在相应的字段中。 我已尝试使用此Stack Overflow答案作为模型,但没有任何运气: https : //stackoverflow.com/a/16806510/640508

我正在使用Controller As语法。

这是我改编的代码:

控制器:

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

服务:

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',
  //. . . 
]);

工厂formMemory返回一个带有3个函数的匿名对象。 您没有使用正确的语法访问这些功能。

要访问保存的数据,您需要将控制器变量设置为get()函数的返回值,如下所示:

contactForm.contact = formMemory.get();

并且要保存数据(如果您导航离开),则应将contact作为参数传递给set(value) 您最有可能在$routeChangeStart执行此$routeChangeStart

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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