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 9.4 illustrates a basic example of implementing $cacheFactory
in a Module
object and then accessing it from two different controllers.
Get Learning AngularJS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.