简体   繁体   English

使用AngularJS中的vm将数据存储到数组中

[英]Storing Data into an Array Using vm in AngularJS

I am storing data into an array but when I refresh the page, the data disappears on my page. 我将数据存储到数组中但是当我刷新页面时,数据会在我的页面上消失。

This is my JS code: 这是我的JS代码:

function VideoController () {
  var vm = this;

  vm.videos = [];

  vm.addVideoUrl = function(text) {
  vm.videos.push(angular.copy(text)); //HOW I AM TRYING TO SAVE DATA INTO MY ARRAY, VIDEOS
}

}

Every time you refresh a new instance of the controller is created. 每次刷新控制器的新实例都会被创建。 Therefor the array is reinitialized to be empty. 因此,阵列被重新初始化为空。

You can use the browser's local storage for storing and getting your data. 您可以使用浏览器的本地存储来存储和获取数据。

You can use $cookies ( https://docs.angularjs.org/api/ngCookies/service/$cookies ) to temporarily save data. 您可以使用$cookieshttps://docs.angularjs.org/api/ngCookies/service/$cookies )临时保存数据。 This is preferable over local storage because it has an expiry time by default. 这比本地存储更可取,因为它默认具有到期时间。

You can use localstorage or sessionstorage , see here the diferences. 您可以使用localstoragesessionstorage ,请参阅此处的差异。

The following example demonstrates how to use it for your case 以下示例演示了如何将其用于您的案例

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    var saveVideosToStorage = function(){
      localStorage.setItem('videos', angular.toJson($scope.videos));
    } 

    var init = function() {
      //load video array from localstorage/sessionStorage
      var videos = angular.fromJson(localStorage.getItem('videos')); 
      if (!(videos instanceof Array)) {
          //videos has been corrupted
          $scope.videos = [];
          saveVideosToStorage();
      }

      $scope.videos = videos;
    }

    var addVideoUrl = function(text) {
      $scope.videos.push(angular.copy(text)); //HOW I AM TRYING TO SAVE DATA INTO MY ARRAY, VIDEOS
      saveVideosToStorage();
    }

    $scope.addVideoUrl = addVideoUrl;
    init();
  }]);

and the markup 和标记

<div ng-repeat="video in videos track by $index">{{video}}</div>
    <input ng-model="videoUrl" type="text"/>
    <input type="button" ng-click="addVideoUrl(videoUrl);">

And here is the plunker 而这里是掠夺者

NOTE: 注意:

I used %scope instead of the var vm = this 我使用%scope而不是var vm = this

I have found an explanation about localStorage, sessionStorage and cookies that is easy to understand see it here . 我发现有关的localStorage,sessionStorage的和饼干的解释,很容易理解看它这里

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

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