我试图将数组存储在AngularJS的$ cacheFactory中。当我尝试获取数组时,它返回的是未定义的。

这是我的代码:

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


...还有Plunker。

有什么想法我做错了吗?

最佳答案

我相信您对$scope.cache.put(myArray, $scope.myArray);这行代码感到困惑,其中myArray是未定义的,并且代码抛出错误,而不是提供一些密钥可以解决您的问题。

$cacheFactory.put(key, value)方法总是以键值格式(例如字典)存储值,然后您可以访问给出其键的值以获取方法,例如$cacheFactory.get(key)



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

希望这可以帮助您,谢谢。

10-06 01:12