How to Have an Image Placeholder in Angularjs

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" />

AngularJS - showing placeholder if image doesn't exist

I would create a directive that replaces the src attribute, like ng-src does, and internally handles the logic you currently have in your imageURL function.

If the directive is named image-url then the markup would look something like this:

<img image-url="listing">

And your directive would look something like this:

app.directive('imageUrl', function () {
return {
scope: {
imageUrl: '='
},
link: function (scope, element, attrs) {
var imageUrl;
if (angular.isUndefined(scope.listing._id) || angular.isUndefined(scope.listing._source.filename1)) { //No image
imageUrl = placeholderImage; //We want to show placeholderImage
}
else {
imageUrl = "/" + scope.listing._id + "/" + scope.listing._source.filename1; // Set the src attribute
}
element.attr("src", imageUrl); // Set the src attribute
}
};
});

You really don't want to bind directly to the src attribute for reasons described in the ngSrc documentation

How do I get a placeholder image to load when my image is still loading from server

isImgLoaded:bool = false;
<img *ngIf="!isImgLoaded" src="assets/images/profileimage.png" >
<img [hidden]="!isImgLoaded" [src]="user.image" (load)="isImgLoaded = true" >


Related Topics



Leave a reply



Submit