How to show a placeholder-image before the real image is downloaded?
You'd probably want to create a directive, I'd actually have hires as the attribute, so that by default it starts with lores.
JS:
app.directive('hires', function() {
return {
restrict: 'A',
scope: { hires: '@' },
link: function(scope, element, attrs) {
element.one('load', function() {
element.attr('src', scope.hires);
});
}
};
});
HTML:
<img hires="http://localhost/hi-res-image.jpg" src="http://localhost/low-res-image.jpg" />
Simple examle. try this, without using directives
HTML
<img ng-src="{{loading.image_url}}" >
Javascript
//within controller
$scope.loading.image_url = 'path_to_loading_image';
var loaded_img = 'path_to_loaded_image';
$http.get(loaded_img).then(function() {
$scope.loading.image_url = loaded_img;
}, function() {
console.log('something went wrong!');
});
Because ng-src
is going to replace whatever is in src
why not use both?
<img src="img/placeholder.jpg" ng-src="{{actualone.img}} " height="150px " width="300px ">
Use normal src
for your placeholder. It will get replaced one the image for ng-src is ready.
The above answer is misleading and here's why. You need to unbind the load event as it will cause infinite load loop on desktop and mobile browsers if you run it in an ng-repeat directive each src replacement will cause new load event to fire and therefore replacement of image etc. The above answer caused my app to break not only performance wise but also caused crashes on mobile devices until I added the unbind.
.directive('imageloaded', function () {
return {
restrict: 'A',
scope:{imageloaded:'@'},
link: function postLink(scope, element, attrs) {
element.bind('load', function() {
//console.log('load fired') <- just console log it and comment the unbind and you will see the 10000s of console logs.
element.attr('src', scope.imageloaded);
element.unbind('load');
});
}
};
});