Explain Codes LogoExplain Codes Logo

Image loaded event in for ng-src in AngularJS

javascript
image-loading
angularjs
error-handling
Alex KataevbyAlex KataevΒ·Aug 6, 2024
⚑TLDR

In AngularJS, you deploy a directive to detect when an image, loaded with ng-src, is fully loaded. The load event is attached to the img element:

app.directive('imageOnLoad', function() { return { restrict: 'A', link: function(scope, element) { element.on('load', function() { // Notice: Image fully loaded, party on πŸŽ‰! scope.$evalAsync('whenLoaded()'); element.on('error', function() { // Uh-oh... Image load failed, it's not our day... scope.$evalAsync('onLoadFailed()'); }); }); } }; });

Apply it in your HTML:

<img ng-src="{{imageUrl}}" image-on-load>

Just swap out whenLoaded() and onLoadFailed() with the actual functions you want to trigger on successful and failed image loads.

iScroll - Preventing Scroll Rage

Is your image nested inside a scrollable container? For instance, a container steered by iScroll? Keep your users scrolling smoothly by updating the scroller right after images load. This neatly adjusts the area's scroll extent:

app.controller('MyController', function($scope) { $scope.whenLoaded = function() { if (iScrollInstance) { // Image loaded, iScroll can chill now ✌ iScrollInstance.refresh(); } }; });

In this snippet, the iScrollInstance.refresh() function springs into action each time an image successfully loads.

Oops, Now What? Handling Image Load Errors

For a fault-tolerant AngularJS image loading directive, integrate error handling to cater for images that fail to load:

app.directive('imageOnLoad', function() { return { restrict: 'A', link: function(scope, element) { element.on('load', function() { // All systems go, image load successful! πŸš€ scope.$evalAsync('whenLoaded()'); }).on('error', function() { // Brace yourselves, we have an image load failure! 🚫 scope.$evalAsync('onLoadFailed()'); }); } }; });

Put up an alternate image or a customized message when an image can't load by defining a suitable onLoadFailed() function in your scope.

The Swiss Knife Directive: Advanced Usage

Spruce up the directive to accept dynamic callbacks:

app.directive('imageOnLoad', function() { return { scope: { whenLoaded: '&', // Dynamic success callback function onLoadFailed: '&' // Dynamic error handling function }, link: function(scope, element, attrs) { element.on('load', function() { // Yep, the image just did a mic drop, it has loaded successfully! scope.whenLoaded(); }).on('error', function() { // Houston, we have an image load problem! scope.onLoadFailed(); }); } }; });

By binding callbacks to the scope, the directive becomes more flexible, letting you assign specific functions for different <img> tags:

<img ng-src="{{imageUrl}}" image-on-load when-loaded="imageLoaded()" on-load-failed="imageLoadFailed()">