Using the $cacheFactory Service

The $cacheFactory service provides a very handy repository for temporarily storing data as key/value pairs. Because $cacheFactory is a service, it is available to multiple controllers and other AngularJS components.

When creating the $cacheFactory service, you can specify an options object that contains the capacity property—for example {capacity: 5}. By adding this capacity setting, you limit the maximum number of elements in the cache to five. When a new item is added, the oldest item is removed. If no capacity is specified, the cache continues to grow.

Listing 25.4 illustrates a basic example of implementing $cacheFactory in a Module object and then accessing it from two different controllers.

Listing 25.4 service_cache.js: Implementing a $cacheFactory service in an AngularJS application


01 var app = angular.module('myApp', []);
02 app.factory('MyCache', function($cacheFactory) {
03   return $cacheFactory('myCache', {capacity:5});
04 });
05 app.controller('myController', ['$scope', 'MyCache',
06                                 function($scope, cache) {
07     cache.put('myValue', 55);
08   }]);
09 app.controller('myController2', ['$scope', 'MyCache',
10                                  function($scope, cache) {
11   $scope.value = cache.get('myValue'),
12 }]);


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.193.255