1

I have a system that generates QR codes for an invoice. The image for the QR code is pulled from another service online.

For my view I have

 <div class="jumbotron" ng-show="invoiceReady">

.. where I set invoiceReady to true once my JS calculates the various amounts.

    $scope.qrImgUrl = 'http://www.btcfrog.com/qr/bitcoinPNG.php?address=' + $scope.invoiceData.btcAddress + '&amount=' + $scope.invoiceData.btcAmount;
    $scope.invoiceReady = true;

But what I need to do is wait a little longer until the image loads in my view. As ng-show shows the invoice view.. but it takes a few seconds longer for the QR image to actually load.

<img ng-src="{{qrImgUrl}}" />

I could use $timeout to wait a couple more seconds to cover that image load time. And I'm curious if there is a way to programatically catch when the image actually does load?

magician11
  • 4,234
  • 6
  • 24
  • 39
  • 1
    possible duplicate of [Image loaded event in for ng-src in AngularJS](http://stackoverflow.com/questions/17884399/image-loaded-event-in-for-ng-src-in-angularjs) – hutingung Oct 23 '14 at 06:12
  • yip using that directive approach worked beautifully. – magician11 Oct 23 '14 at 08:27

2 Answers2

2

Solution I found was to use a directive as shared by @hutingung above. And modified from the code I found here https://thinkster.io/egghead/directives-talking-to-controllers/

Create a directive..

angular.module('posBitcoinApp')
.directive('imageonload', function () {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        element.bind('load', function() {
            scope.$apply(attrs.imageonload);
        });
    }
};
});

In my view..

<img ng-src="{{qrImgUrl}}" imageonload="showInvoice()"/>

Then in my controller..

$scope.showInvoice = function() {
    $scope.invoiceReady = true;
};
magician11
  • 4,234
  • 6
  • 24
  • 39
0

The ngSrc directive won't help you with this, because basically it does nothing more than setting the src attribute of an img element.

However, there are ways of being notified when an image has loaded: see How can I determine if an image has loaded, using Javascript/jQuery?

Community
  • 1
  • 1
Valentin Waeselynck
  • 5,950
  • 26
  • 43