AngularJS中ng src的图像加载事件

Image loaded event in for ng-src in AngularJS

本文关键字:图像 加载 事件 src ng AngularJS      更新时间:2023-09-26

我的图像看起来像<img ng-src="dynamically inserted url"/>。当加载单个图像时,我需要应用iScroll refresh()方法,以便使图像可以滚动。

当图像被完全加载以运行回调时,最好的方法是什么?

下面是一个如何调用image onload的示例http://jsfiddle.net/2CsfZ/2/

基本思想是创建一个指令并将其作为属性添加到img标记中。

JS:

app.directive('imageonload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
            });
            element.bind('error', function(){
                alert('image could not be loaded');
            });
        }
    };
});

HTML:

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

我对此进行了一些修改,以便可以调用自定义$scope方法:

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

指令:

.directive('imageonload', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element.bind('load', function() {
                    //call the function that was passed
                    scope.$apply(attrs.imageonload);
                });
            }
        };
    })

希望有人觉得它很有用。谢谢@mikach

doThis()函数将是$scope方法

@Oleg Tikhonov:刚刚更新了以前的代码。。@米卡奇谢谢…)

app.directive('imageonload', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('load', function() {
            alert('image is loaded');
        });
        element.bind('error', function(){
             alert('image could not be loaded');
        });
    }
  };
});

我的答案:

 var img = new Image();
 var imgUrl = "path_to_image.jpg";
 img.src = imgUrl;
 img.onload = function () {
      $scope.pic = img.src;
 }

刚刚更新了以前的代码。。

<img ng-src="{{urlImg}}" imageonload="myOnLoadImagenFunction">

和指令。。。

    .directive('imageonload', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element.bind('load', function() {
                    scope.$apply(attrs.imageonload)(true);
                });
                element.bind('error', function(){
                  scope.$apply(attrs.imageonload)(false);
                });
            }
        };
    })

基本上这就是我最终使用的解决方案。

$apply()只能由外部源在正确的情况下使用。

我没有使用apply,而是将作用域更新抛出到调用堆栈的末尾。与"scope.$apply(attrs.imageonload)(true);"一样有效。

window.app.directive("onImageload", ["$timeout", function($timeout) {
    function timeOut(value, scope) {
        $timeout(function() {
            scope.imageLoaded = value;
        });
    }
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                timeOut(true, scope);
            }).bind('error', function() {
                timeOut(false, scope);
            });
        }
    };
}]);