Image loaded event in for ng-src in AngularJS
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:
Apply it in your HTML:
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:
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:
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:
By binding callbacks to the scope, the directive becomes more flexible, letting you assign specific functions for different <img>
tags:
Was this article helpful?