AngularJS中ng src的图像加载事件
Image loaded event in for ng-src in AngularJS
我的图像看起来像<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);
});
}
};
}]);
相关文章:
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 在检索数据时是否可以停止图像加载请求
- 如何让我的网站上的WEBP图像加载在morzilla firefox中有一个可能的解决方案吗?如果是,那么如何
- jQuery:获取图像加载错误的详细信息
- 在safari和chrome中,js图像加载产生了奇怪的结果
- 图像加载不适用于 IE 8 或更低版本
- 这个图像加载功能有什么作用
- JavaScript 图像加载器不起作用
- 动态图像加载是否会减少服务器过载
- 跨来源图像加载被拒绝-仅限iPhone-简单图像上传
- 纯javascript的进度图像加载程序仅当用户单击提交html表单时
- 使用JavaScript延迟图像加载
- 如果当前图像加载缓慢,如何加载其他图像
- HTML图像加载触发一个错误
- 将图像加载到localStorage,并将图像src设置到该位置
- jquery图像加载检查错误
- 将图像加载到织物画布背景中
- 需要在bootstrap css中单击时将图像加载为模态
- 正在显示加载..在将新图像加载到网站时播放动画
- 砖石事件:在图像加载和布局完成后调用事件