user3718908x100
user3718908x100

Reputation: 8509

Set default image before actual image is loaded

In my application, several images are loaded, however when the view is opened, you can clearly see each image being loaded, by this I mean the top half of the image appears and it keeps increasing till the full image is displayed. I do not want this.

My images are inside an ng-repeat, what i want to do is when the page is loaded all images are set to a default image that comes bundled with the app. Now after my function has returned all new image URLs and those images have been fully loaded then they should replace the default images.

So basically like this:

  1. Open view
  2. Set all images to default.jpg
  3. Get data.
  4. Wait for new images to load fully.
  5. Replace default images with new image URL fetched from the server.

I have never done this before and do not know how to go about it.

Upvotes: 1

Views: 2392

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

You can write like this:

<div ng-repeat="user in users">
    {{user.name}}<br>
    <img src="/images/foo/demp/default.png" actual-image="{{user.avatar}}" />
</div>

Then you can use a directive like:

myApp.directive('actualImage', ['$timeout', function($timeout) {
    return {
         link: function($scope, element, attrs) {
             function waitForImage(url) {
                 var tempImg = new Image();
                 tempImg.onload = function() {
                     $timeout(function() {
                         element.attr('src', url);
                     });
                 }
                 tempImg.src = url;
             }

             attrs.$observe('actualImage', function(newValue) {
                 if (newValue) {
                     waitForImage(newValue);
                 }
             });
         }
    }
}]);

Upvotes: 5

Related Questions