1

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
}

}
jaahvicky
  • 438
  • 2
  • 8
  • 20
  • we need more information. however it seems the controller is attached to your view -> it loads every time you refresh the page and sets vm.videos to [] – niklas Mar 23 '16 at 11:08

3 Answers3

3

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.

Saar Kuriel
  • 572
  • 4
  • 16
0

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.

cani
  • 91
  • 7
  • Remember that cookies size is limited, try not to store too much data there. User can have also cookies disabled on his browser - just a thing to remember. – Jacob Sobus Mar 23 '16 at 11:17
0

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.

Community
  • 1
  • 1
Jose Rocha
  • 1,115
  • 7
  • 20