如何从保存在localstorage中的数据填充表单

时间:2015-07-01 04:32:58

标签: javascript angularjs html5 forms local-storage

我想用我保存在localstorage中的这个值填充一个表单。

var vm;
  vm = this;
  vm.data = {};

  var memberData = JSON.parse(localStorage.getItem('memberData'));
  vm.data.mobile =  memberData.mobile;

这是我想要填充的表单:

<div class="item item-icon-left"><i class="icon ion-iphone assertive"></i><span  class="label">Mobile</span><span class="item-note">
 <input type="tel" name="mobile" placeholder="Contact" ng-model="profile.data.mobile" required="required" style="background-color:transparent;"/>
  <div class="helpers" ng-if="profileForm.mobile.$touched">
                  <span ng-if="profileForm.mobile.$error.required" class="help-block" style="color:red;">Enter a Phone No.!</span>
                  </div>
                </span>
                </div>

2 个答案:

答案 0 :(得分:0)

如果您的表单是示例中的输入标记,则可以通过选择元素并将value属性设置为您想要的属性来轻松完成,例如(在您的情况下):

  // since your input has no ID, we'll use getElementsByName instead
  // this returns an array of elements, so we'll choose the first one
  // using an ID would be better practice
  var mobileInput = document.getElementsByName('mobile')[0];

  // then we modify the value attribute with your value from above
  mobileInput.value = vm.data.mobile;

阅读W3 Schools上的属性和其他相关内容,或者查看Mozzila's specs on the input tag以获取有关如何使用JavaScript进行播放的提示!

答案 1 :(得分:0)

您在视图中使用ng-controller="[Controller] as profile"吗?如果没有,那么

vm.data.mobile =

应改为

vm.profile.data.mobile =