Created
March 26, 2013 20:00
-
-
Save inklesspen/5248668 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; /* global angular, $ */ | |
| /* Services */ | |
| angular.module('uploadApp.services', []). | |
| factory('imageloader', ['$q', '$rootScope', function($q, $rootScope) { | |
| // Loads an image offscreen and provides a promise. The promise | |
| // will be resolved with the jQuery object containing the | |
| // image. Only one image can be loaded at a time; a new request | |
| // while the old one is pending will cancel the old one. | |
| // This assumes there is a jquery function $, and a div like | |
| // <div id="imageloader" style="position:absolute; left: -3000px; top: -3000px;"></div> | |
| var imageloader = $("#imageloader"); | |
| var deferred = null; | |
| var cleanup = function() { | |
| imageloader.empty(); | |
| if (deferred != null) { | |
| deferred.reject('cancelled'); | |
| deferred = null; | |
| } | |
| }; | |
| var makeLoad = function(resolve) { | |
| return function() { | |
| resolve(imageloader.find("img")); | |
| deferred = null; | |
| $rootScope.$digest(); | |
| }; | |
| }; | |
| var makeError = function(reject) { | |
| return function() { | |
| reject('loadError'); | |
| deferred = null; | |
| $rootScope.$digest(); | |
| }; | |
| }; | |
| return function(url) { | |
| cleanup(); | |
| deferred = $q.defer(); | |
| var promise = deferred.promise; | |
| var newImg = $("<img>"); | |
| newImg.bind({ | |
| load: makeLoad(deferred.resolve), | |
| error: makeError(deferred.reject) | |
| }); | |
| newImg.attr('src', url); | |
| imageloader.append(newImg); | |
| if (deferred == null) { | |
| } | |
| return promise; | |
| }; | |
| }]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment