AngularJS中的图像加载ng-src中的事件

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

什么是最好的方式知道什么时候图像完全加载运行一些callback?

这里是一个如何调用图像的例子onload http://jsfiddle.net/2CsfZ/2/

基本的想法是创build一个指令,并将其作为属性添加到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:刚刚更新了以前的代码.. @ mikach谢谢..)

 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'); }); } }; }); 

刚更新了以前的代码

 <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); }); } }; }) 

基本上这是我最终使用的解决scheme。

$ 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); }); } }; }]); 

我的答案:

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