2

I'm trying to store an array in AngularJS' $cacheFactory. When I try to get the array it's returning undefined.

Here's my code:

  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("myArray is:");
      console.log($scope.cache.get($scope.myArray));
    }]);

...and Plunker.

Any ideas what I'm doing wrong?

1
  • Are you ever declaring myArray, I see you putting it on $scope, but where is the myArray variable declared? your key is not declared! Commented Feb 25, 2015 at 19:32

1 Answer 1

2

I believe you were messing with $scope.cache.put(myArray, $scope.myArray); this line of code in which myArray is undefined and code was throwing error instead of that give some key will solve your issue.

$cacheFactory.put(key, value) method always stored value in key value format like dictionary & then you can access those value giving its key to get method like $cacheFactory.get(key)

CODE

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));
    });

  }
]);

Working Plunkr

Hope this could help you, Thanks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.