angular img with loading spinner
HTML
<!-- Open Chrome Dev-Tools and set to mobile device with slow network (ex: Regular 3G)
After 1st run, you may need to clear your browser cache to see the effect again (Ctrl+Shift+Del)
Two images will be loaded: a dog, then a cat... with spinners before each load.
--> <p> See comments in HTML </p>
<div ng-controller="c">
<img-with-loading
img-src="{{src}}"
spinner-class="{{spinnerClass}}"
/>
</div>
CSS
.background-spinner {
background-repeat: no-repeat;
background-position: center center;
background-image: url('https://www.yugma.com/images/loading-animation-7.gif')
}
div.imgWithLoading, div.imgWithLoading img {
width: 100%;
}
JavaScript
var app = angular.module('app', []);
/*
<img-with-loading
img-src="{{src}}"
spinner-class="{{spinnerClass}}"
height-multiplier=0.65>
</img-with-loading>
spinnerClass should be something like:
.background-spinner {
background-repeat: no-repeat;
background-position: center center;
background-image: url('https://www.yugma.com/images/loading-animation-7.gif')
}
height-multiplier: this attr sets the height of the container div to a multiple of width
you should set the <img-with-loading> with a desired width and the height
will be set by this attr.
<img> width and height is up to you (ex: set css rule for 'div.xxxx img')
Ex: if width is 90% and happens to be 512px, with height-multiplier=0.65
you will have img with height = 512 * 0.65 = 332.8
*/
app.directive('imgWithLoading', function () {
return {
restrict: 'E',
template: '<div/>',
transclude: false,
replace: true,
scope: {
imgSrc: '@'
},
link: function (scope, element, attrs) {
console.log('imgWithLoading init: source="' + scope.imgSrc + '"');
setHeight();
var img = angular.element(new Image());
var unbind1 = img.on('load', function (evt) {
console.log('image loaded: ' + img.attr('src'));
stopLoadingCSS( );
});
var unbind2 = img.on('error', function(evt) {
console.log('imgWithLoading error Loading ' + scope.imgSrc);
...