imgCache AngularJS directive
Abit on imgCache.js
The purpose of this JS library is to provide a nice interface for locally storing images for offline apps using PhoneGap/Cordova or browsers supporting the new html5 File API (e.g. Chrome).
This library is especially useful for mobile web applications using Phonegap/Cordova where the normal browser cache cannot be relied upon and where offline navigation is quite common.
In your main controller usually app.js, you can put the below code in your .run method.
If the cache successfully initializes, ImgCache.ready will be set to true. You can also watch for the triggeredImgCacheReady event.
If you're using imgcache.js with PhoneGap/Cordova, ImgCache.init() must be called after the onDeviceReadyevent has been triggered, not before!
I'm using mine with Ionic Framework so here's my full .run(['$ionicPlatform', '$rootScope', function($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } //set up and init image caching // write log to console ImgCache.options.debug = true; // increase allocated space on Chrome to 50MB, default was 10MB ImgCache.options.chromeQuota = 50*1024*1024; ImgCache.init(function(){ //small hack to dispatch an event when imgCache is //full initialized. $rootScope.$broadcast('ImgCacheReady'); }, function(){ alert('ImgCache init: error! Check the log for errors'); }); }); }])
For some reason, I could not catch the event imgCache triggers when it initializes. I tried
document.addEventListener('ImgCacheReady', function () { /* your code here */ }, false);
$document.addEventListener('ImgCacheReady', function () { /* your code here */ }, false); $($document).$on('ImgCacheReady')
None worked. That aside, below is the directive.
app.directive('imgCache', ['$document', function ($document) { return { // require: 'ngSrc', link: function (scope, ele, attrs) { var target = $(ele); //waits for the event to be triggered, //before executing d call back scope.$on('ImgCacheReady', function () { //this checks if we have a cached copy. ImgCache.isCached(attrs.src, function(path, success){ if(success){ // already cached ImgCache.useCachedFile(target); } else { // not there, need to cache the image ImgCache.cacheFile(attrs.src, function(){ ImgCache.useCachedFile(target); }); } }); }, false); } }; }]);
Ok cool.. so just add "img-cache" this to any image tag you wish to cache















