AngularJS Image Loaded Directive

A simple directive to check if your images have loaded

Posted on April 5, 2016

Tags:

Angular

I’m currently working on a very large scale AngularJs app which uses Amazon S3 for file storage and came across an issue where the image URLs would timeout and need to be refreshed.

To get around this I wrote a simple directive to check if the image had been loaded and then request a new URL if not.

'use strict';
angular.module('MY_APP_NAME')
    .directive('imageLoaded', function (user) {
        return {
            restrict: 'A',
            link: function postLink(scope, element, attrs) {
	          element.bind('error', function(){
		      // Here I made a request for a new image link and applied it scope. 
	          });
            }
        };
    });

To use the directive just add the attribute to your image tag:

<img ng-src="logo" alt="" image-loaded />