Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-src: show a throbber before an image is loaded

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?

like image 890
mingos Avatar asked Jul 03 '13 13:07

mingos


2 Answers

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();
          }
        });
      }
    };
  });
like image 102
Jason Als Avatar answered Oct 20 '22 16:10

Jason Als


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.

like image 26
Furqan Ahmed Avatar answered Oct 20 '22 16:10

Furqan Ahmed