简体   繁体   中英

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:

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. This is preferable over local storage because it has an expiry time by default.

You can use localstorage or sessionstorage , see here the diferences.

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

I have found an explanation about localStorage, sessionStorage and cookies that is easy to understand see it here .

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