<img ng-src="dynamically inserted url"/>
ฉันมีภาพที่มองเช่น เมื่อโหลดภาพเดียวฉันต้องใช้วิธีการรีเฟรช iScroll () เพื่อให้สามารถเลื่อนภาพได้
วิธีใดที่ดีที่สุดในการทราบเมื่อรูปภาพโหลดจนเต็มเพื่อเรียกใช้การโทรกลับ
<img ng-src="dynamically inserted url"/>
ฉันมีภาพที่มองเช่น เมื่อโหลดภาพเดียวฉันต้องใช้วิธีการรีเฟรช iScroll () เพื่อให้สามารถเลื่อนภาพได้
วิธีใดที่ดีที่สุดในการทราบเมื่อรูปภาพโหลดจนเต็มเพื่อเรียกใช้การโทรกลับ
คำตอบ:
นี่คือตัวอย่างวิธีการเรียก 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()
ฟังก์ชั่นจากนั้นก็จะเป็นวิธีการที่ $ ขอบเขต
@ 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');
});
}
};
});
คำตอบของฉัน:
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 ฉันได้โยนขอบเขตการอัปเดตไปยังจุดสิ้นสุดของ call stack ทำงานได้ดีเท่ากับ "ขอบเขต. $ 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);
});
}
};
}]);
$apply()
ควรใช้โดยแหล่งภายนอกเท่านั้น"? ฉันไม่ได้ติดตาม