【问题标题】:Is there a callback/promise for when images load when using ng-src?使用 ng-src 时加载图像时是否有回调/承诺?
【发布时间】:2014-12-18 17:00:48
【问题描述】:

我有一个生成发票二维码的系统。二维码的图像是从另一个在线服务中提取的。

在我看来,我有

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

.. 一旦我的 JS 计算出各种金额,我将 invoiceReady 设置为 true。

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

但我需要做的就是再等一会儿,直到图像加载到我的视图中。 ng-show 显示发票视图.. 但实际加载 QR 图像需要几秒钟的时间。

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

我可以使用 $timeout 再等待几秒钟以涵盖该图像加载时间。我很好奇是否有办法以编程方式捕捉图像实际加载的时间?

【问题讨论】:

标签: angularjs


【解决方案1】:

我找到的解决方案是使用上面@hutingung 共享的指令。并根据我在这里找到的代码修改https://thinkster.io/egghead/directives-talking-to-controllers/

创建一个指令..

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

在我看来..

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

然后在我的控制器中..

$scope.showInvoice = function() {
    $scope.invoiceReady = true;
};

【讨论】:

    【解决方案2】:

    ngSrc 指令不会帮助您解决这个问题,因为基本上它只是设置img 元素的src 属性。

    不过,有一些方法可以在加载图片时收到通知:请参阅How can I determine if an image has loaded, using Javascript/jQuery?

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 2016-03-29
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多