简体   繁体   中英

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);

If I don't initialize $localStorage.subject as an array, it gives me an error that says .push is not a function .

Why does it not give this error when I push data to $localStorage.address ?

You use:

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);

or you just declare:

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

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