Storing an array in $cacheFactory with AngularJS

Having some trouble saving an array in AngularJS' $cacheFactory. When attempting to retrieve the array, it's coming back as undefined.

Here is the code snippet:

  angular.module('cacheExampleApp', []).
    controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
      $scope.myArray = [
        "one",
        "two",
        "three"
      ];
      $scope.keys = [];
      $scope.cache = $cacheFactory('cacheId');
      $scope.put = function(key, value) {
        $scope.cache.put(myArray, $scope.myArray);
        $scope.keys.push(key);
      };
      console.log("Checking myArray:");
      console.log($scope.cache.get($scope.myArray));
    }]);

...along with a Plunker link.

Any suggestions on what's causing this issue?

Answer №1

It seems like there was an issue with the line of code where you were using

$scope.cache.put(myArray, $scope.myArray);
. The error occurred because myArray was undefined. To resolve this issue, you need to provide a key for storing the value.

The $cacheFactory.put(key, value) method functions by storing values in a key-value format similar to a dictionary. You can then access these values by providing the key to the $cacheFactory.get(key) method.

EXAMPLE

angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory',
  function($scope, $cacheFactory) {
    $scope.myArray = [
      "one",
      "two",
      "three"
    ];
    $scope.keys = [];
    $scope.cache = $cacheFactory('cacheId');
    $scope.put = function(key, value) {
      $scope.cache.put(key, value);
      $scope.keys.push(key);
    };
    $scope.put("myArray", $scope.myArray);
    $scope.put("myArray1", $scope.myArray);
    $scope.put("myArray2", $scope.myArray);
    angular.forEach($scope.keys,function(value, index){
      console.log(value + " is:");
      console.log($scope.cache.get(value));
    });

  }
]);

Check out the working example on Plunkr

Hopefully, this explanation helps resolve your issue. Thank you.

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

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

What is the best method to trigger a reevaluation of static parameters?

Explanation behind my question Every day, I am sent two timestamps through MQTT at 01:15 - these timestamps represent the beginning and end of a daily event (in this case, when my children are at school). It may not be the most exciting information for a ...

What is the recommended Vue js lifecycle method for initializing the materialize dropdown menu?

https://i.stack.imgur.com/cjGvh.png Upon examining the materialize documentation, it is evident that implementing this on a basic HTML file is straightforward: simply paste the HTML code into the body and add the JavaScript initializer within a script tag ...

Implementing mouse event listeners on dynamically created elements in Vue.js

I've been curious if anyone has attempted something similar to the following code snippet (created within a Vue.js method): for (let i = 0; i < this.items.length; i++) { let bar = document.createElement('div'); bar.className = this ...

I am unable to incorporate added height into the component

In my current project using react.js, material-ui, and sass, I had the task of creating a ChatBit component. After writing it, here is the code: customComponent.js file. // @flow import * as React from 'react'; import { useState } f ...

how to save an array within an ArrayList in Java

I have been attempting to save an array within an ArrayList using a method like the one shown below: static ArrayList<double []> Shapes; public static void Test(){ double [] Test = new double [2]; Test[0] = 1; Test[1] = 2; Shapes.add ...

What is the best way to organize and structure a node.js project for modularity?

In the process of developing a node.js project, I am adhering to the class constructor pattern as shown below: function my_class(x,y){ this.x = x; this.y = y; } The foundation of the project lies within the main.js file. It is imperative that any ...

The error message encountered with React Easy DatePicker is: "Uncaught ReferenceError: process is not defined."

I am attempting to integrate the stylish DatePicker from https://www.npmjs.com/package/sassy-datepicker?activeTab=readme Here is my implementation : import DatePicker from "sassy-datepicker"; function App() { const [date, setDate] = useSta ...

Adjusting the range input value in AngularJS

The value and position of the range should dynamically change based on the parameter without the need for the parameter to be manually updated HTML: <body ng-app="myApp"> <div ng-controller="MyRngCtrl"> Param:{{param}} </d ...

Tips for inserting data at targeted levels within a MongoDB document

Looking at a MongoDB Document: { "_id" : ObjectId("553e0c2ec9ad2dbe13cc17cc"), "country" : "ireland", "games" : [ { "title" : "Test", "draws" : [ ] }, { ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

What is the best practice for storing a SQLITE database file in electron when in production mode?

Currently, I am developing a portable Node.js server using Electron and utilizing an SQLITE database for data storage. During development, the database file test.db is placed in the same directory as my Main.js file, which works perfectly. However, when I ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

ASP not recognizing AngularJS input states

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Staffing_Tool.Login" %> <!DOCTYPE html> <html> <head runat="server"> <script src="scripts/angular.min.js" type="text/javascript"></scr ...

Create a versatile and reusable function that can adapt to different situations

I am struggling to implement the sendMessage function in another method. Here is an example of what I need: SendMessage('[email protected]','[email protected]','subject','body'). As a newcomer to nodejs, ...

Positioning pop-up windows using Javascript and CSS techniques

In my web application, there is a search field that allows users to enter tags for searching. The window should pop up directly below the search field as shown in this image: Image I am trying to figure out how the window positioning is actually d ...

Vuejs unstyled content flash

I encountered an issue while loading a page with Vue. Initially, I am able to access variables like @{{ value }} but once the page is fully loaded, the variable becomes invisible. How can I resolve this issue? I have already included Bootstrap and all scri ...

What is the best way to update the key for the sorting field in a meteor collection query?

I am struggling to replace the name key with a value passed in via a parameter this.params.sortby in the code below. Any help would be appreciated. For example, if: this.params.sortby=location I would like the following: Template.MyTemplate.helpers({ ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

Using the $.ajax function with the PUT method and sending an OPTIONS request

Here is my code snippet: function test(segmentId) { var url = "http://...../api/avoidsegments/123456"; $.ajax({ url: url, type: "PUT", contentType: "application/json", data : { "appID": ig_appID, ...