How to Save Information in an Array with AngularJS' vm functionality

Every time I save data into an array, it seems to disappear when I refresh the page.

Here is the JavaScript code that I am using:

function VideoController () {
  var vm = this;

  vm.videos = [];

  vm.addVideoUrl = function(text) {
    vm.videos.push(angular.copy(text)); // This is how I attempt to store data in my 'videos' array
  }
}

Answer №1

Each time the page is refreshed, a new controller instance is generated, resetting the array to empty.

Utilize the local storage of the browser to store and retrieve your data efficiently.

Answer №3

To store data locally in your browser, you have the option of using localstorage or sessionstorage. You can check out the differences between them here.

This code snippet illustrates how to implement this for your specific scenario:

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

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

      $scope.videos = videos;
    }

    var addVideoUrl = function(text) {
      $scope.videos.push(angular.copy(text)); // Save new data into 'videos' array
      saveVideosToStorage();
    }

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

Here is the corresponding 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);">

You can view the working example on Plunker.

NOTE:

In this code snippet, I used $scope instead of declaring a variable like var vm = this.

If you need a more straightforward explanation about localStorage, sessionStorage, and cookies, check it out here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There was an issue encountered while parsing the JSON data - "SyntaxError: Unexpected token . was caught."

Encountering an error in Chrome while parsing JSON data. The JSON sample can be found at this link. It is valid JSON and the server is sending the correct Content-Type value (application/json). Uncaught SyntaxError: Unexpected token . Firefox shows a sli ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

Tips for clearing the browser cache when working with AngularJS in HTML code

Does anyone know how to clear the browser cache in HTML when using AngularJS? I've tried adding the following code to my index.html file and also used $templateCache in my app.js without success. <meta http-equiv="Cache-Control" content="no-cache, ...

Mastering AngularJS Date Formatting

My date is currently in this format: 2015-02-19 00:00:00 I am looking to format it to: 19-02-2015 I attempted the following: sc.documents.datestring = $filter("date")('2015-02-19 00:00:00', 'dd-MM-yyyy'); Unfortunately, that metho ...

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...

Ways to retrieve data from various MongoDB collections in state with Express?

MongoDB Relationship Dilemma Trying to implement a many-to-many relationship in MongoDB, I am faced with the challenge of reading documents from multiple collections within the same database. Within my backend script server.js, I am fetching data from col ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

The error message "prettyPrint is not defined" indicates that the function prettyPrint

I am facing an issue with ReferenceError: prettyPrint is not defined. Can you provide some help? <a class="question helpcenterheading" href="http://www.google.com">How do I reach out to you?</a> <span class="answer">Just a moment...</ ...

Modify the values within all deeply nested objects using Immutable.js

The reducer code snippet given below illustrates the structure: import {ADD_TASK, EDIT_TASK, CHECK_TASK, CHECK_ALL_TASK} from '../constants'; import {OrderedMap, Record} from 'immutable'; const TaskRecord = Record({ id: null, ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

Is there a way to transform individual data into a collective group dataset?

Here is the input data provided: data = [ { name: "John Cena", groupName: "WWE" }, { name: "Nandini", groupName: null }, { name: "Rock", groupName: "WWE" }, { name: "Vinay", groupName: null }, { name: "Rey Mesterio", groupName: "WWE" ...

Unable to bring in Vue component from NPM module

Hello there, I recently developed my own npm package for a navigation bar and I need to incorporate it into my main codebase. Currently, I am utilizing vue @components but I am struggling with integrating the imported component. If anyone has insight on h ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The fina ...

Enhance your Vue.js application by dynamically adding a class when a computed value

Just delving into the world of vue.js and I have a simple query. I've been following a tutorial but now I'd like to add my own touch to it :-P Whenever there is a change in my rank, I would like to include a CSS class for animating the label. Ho ...

What is the best way to share information among Vue3 single file component instances?

I am seeking a way to have certain data in my single file component shared among all instances on the page, similar to how static variables work in PHP/C. To achieve this, I understand that in single file components, we declare data as a function like so: ...

JQuery click function not triggering the event

Here is the situation I am dealing with. On my index.php page, I have included the following JQuery code: jQuery(document).ready(function(){ jQuery('#sIMG img').click(function() { var currentSRC = jQuery(this).attr('src'); ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

The function you are trying to access is not Random-js

Everything was running smoothly, but now there seems to be a glitch. Node version - 10.4 Error: var random = require("random-js")(); ^ TypeError: require(...) is not a function Code: var random = require("random-js")(); ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...