繁体   English   中英

为什么$ localStorage中的数组有效

[英]Why is an array in $localStorage working

index.html

<div class="modal-body">
   <form >
      <tags options="{addable: true}" typeahead-options="typeaheadOpts" data-model="information.address" data-src="toPerson as toPerson for toPerson in to"></tags>
      <input type="text" placeholder="Subject" style="width:95%;" data-ng-model = "information.subject"><br />
      <textarea style="width:95%;" rows="10" data-ng-model = "information.emailContent"></textarea>
   </form>
</div>

<div class="modal-footer">
   <a href="#" class="btn" ng-click = "submit(information.address, information.subject, information.emailContent); close()">Close</a>
   <a href="#" class="btn btn-primary" ng-click = "close()">Send</a>
</div>

emailViewController.js

$scope.information = {
      address: [],
      subject: []
   };

$scope.submit = function (address, subject, emailContent) {
   $localStorage.address.push(address);

   if (! ($localStorage.subject instanceof Array) ) {
      $localStorage.subject = [];
   }

   $localStorage.subject.push(subject);

如果我没有将$localStorage.subject初始化为数组,则会给我一个错误,提示.push is not a function

当我将数据推送到$localStorage.address时,为什么没有给出此错误?

你用:

var Helper = {
    pushArray: function (arr1, arr2) {
        arr1 = this.toArray(arr1);
        if (arr1 && arr2 && Array.isArray(arr1)) {
            arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);
        }
    },

    toArray: function (arr) {
        return arr ? (Array.isArray(arr) ? arr : [arr]) : [];
    }
};
Helper.pushArray(arr1, second);

或者您只声明:

$localStorage.$default({
   subject: []
});

暂无
暂无

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

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