I wanted to know how to implement a image cache in AngularJS, or a way to load the image once and use it many times in the same application
I have to show a directory listing in ui-select . The drop down may contain folders or files. For folders I want to show a folder icon and for files I want to show a file icon. I am using ng-repeat to iterate the array of files and folders
[ {name: "abc/", folder: true}, {name: "pqr.txt", folder: false}, ......]
Inside the ng-repeat, I have a ng-if which shows a folder icon, if folder-attribute is true else it shows a file-icon. Right now, I am using tag to load the image. The image is in my local directory, will it slow down the performance? Should I use a cache?
If you are not using through an
$http
service you might use the $cacheFactory service that generates cache objects for all Angular services. Internally, the $cacheFactory creates a default cache object, even if we don’t create one explicitly.Then you can use the the
put
method which allows to to put a key (string) of any JavaScript object value into the cache.You can access it by
Or if you are using through $http service you can enable the cache by setting the
cache
parameter as true:For anyone coming here from a Cordova/Phonegap + Angular mix; I was running into the issue where I didn't like any of the solutions available and the seemingly popular solution of the christen/imgcache plugin wasn't worth following due to lack of OS support (Looks like chrome is the only OS supported) https://github.com/chrisben/imgcache.js/
So I decided to write an AngularJS directory that handles the entire process simply by adding a "cacheimg" attribute on any img/element with background image.
The basics of the following are that it downloads and writes the image files into temporary storage on the device using the cordova file + filetransfer plugins (Both are required for this plugin to work!)
So for anyone unsure how to handle the above (and I apologise if this method is not 'very angular' - I'm still fairly new to Angular myself!) simply copy the code, stick it into a new file in your projects js folder, make sure you include this file in the project:
Change the "app.directive" to be [yourappname].directive, you can then just add the attribute "cacheimg" to your element...
For the purpose of the last example I had to stick in a $watch because the directive gets called prior to the background image being set! If you don't plan on setting an image from a scope variable I strongly recommend removing the $watch!
It is also worth mentioning that currently I haven't put in a delete - it is good practise to not rely on the OS to delete files so I plan on adapting this directory further to remove any image not requested for a while.
Anyway, hope that helps someone! :)
As long as your image is coming from the same URL, your browser will do the caching automatically.