angular.js - sharing cacheFactory data between blocks

advertisements

I want to share the same $cacheFactory between .run block and a service. I defined a $cacheFactory in my .run block :

var cache = $cacheFactory('cacheName');

and put some stuff inside:

cache.put('appData', data);

then I want to check if the key exsits in one of my services but the error I get is - CacheId 'CacheName' is already taken!

Here is the service code:

$scope.cache = $cacheFactory('cacheName');
if (angular.isUndefined($scope.cache.get(key))) {
   $log.log($scope.cache.get(key)); //printing th key
}

so how do I share cache data?


Hard to say without seeing the rest of your code. But my example below works

(function(angular) {
  'use strict';

  angular
    .module('cacheExampleApp', [])
    .controller('CacheController', ['$scope', '$cacheFactory', 'notify', function($scope, $cacheFactory, notify) {

      $scope.cache = $cacheFactory('cacheName');
      $scope.cache.put('appData', 'some data');

      $scope.callNotify = function() {
        notify();
      };

    }])
    .factory('notify', ['$window', '$cacheFactory', function(win, $cacheFactory) {

      return function() {
        var dataCache = $cacheFactory.get('cacheName');
        win.alert(dataCache.get('appData'));
      };

    }]);

})(window.angular);

Example: https://plnkr.co/edit/axiPg5qzxLTyGLy8pMu1?p=preview