I have implemented an interface where the user can cycle through a set of images by clicking buttons. The image URLs are stored in an array and are replaced by angular.js dynamically:
<img ng-src="{currentUrl}">
However, the requests for consecutive images tend to lag a bit and the image change isn't apparent since the previous image is displayed until the new one arrives.
I would like to replace the image with a throbber (animated gif). How can I achieve that using Angular.js?
you can do this with a directive which replaces your image with a spinner whenever the path changes and shows the image when it is loaded.
<img my-src="{{currentUrl}}">
app.directive("mySrc", function() {
return {
link: function(scope, element, attrs) {
var img, loadImage;
img = null;
loadImage = function() {
element[0].src = "pathToSpinner";
img = new Image();
img.src = attrs.mySrc;
img.onload = function() {
element[0].src = attrs.mySrc;
};
};
scope.$watch((function() {
return attrs.mySrc;
}), function(newVal, oldVal) {
if (oldVal !== newVal) {
loadImage();
}
});
}
};
});
I know its pretty late but i do it like
<img src="img/loader.gif" ng-src={{dynamicImageURL}}>
by default your loader img will show and later when dynamicImageURL gets resolved, the image will be replaced by angular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With