[英]AngularJS check image for 404 and get dynamic URL for image src
這是我的中繼器:
<div ng-click="selected(entity)" ng-if="entity.is_organization == true">
<div class="row">
<div class="cell info">
<span class="text" ng-bind-html="entity.label"></span>
</div>
<div class="cell img" ng-show="isImageAvailable">
<img class="image" ng-src="checkImageAvailable(entity.thumbnail[0])">
</div>
</div>
</div>
checkImageAvailable
中的checkImageAvailable
:
$scope.isImageAvailable = false;
$scope.checkImageAvailable = function(image_url){
var img = new Image();
img.onload = function (){
$scope.isImageAvailable = true;
};
img.onerror = function (){
$scope.isImageAvailable = false;
};
img.src = image_url;
if($scope.isImageAvailable){
return image_url;
}
};
我從JSON獲得了entity.thumbnail[0]
,但即使它具有一個URL,它也不存在。 所以我確實使用checkImageAvailable
檢查它。 如果圖像不可用,請將isImageAvailable
設置為false,因此圖像父容器ng-show
會注意從瀏覽器隱藏圖像占位符。 在控制台日志上同時顯示: http://localhost/checkImageAvailable(entity.thumbnail[0])
為404
我在AngularJS之前犯的錯誤可能是什么。
一件錯誤的事是您設置的時間:
$scope.isImageAvailable = true; //or false
您不在角度生命周期內-因此您必須調用$scope.$apply()
;
每當您在角度事件之外更改角度范圍時,都必須調用$apply()
。
檢查isImageAvailable可能為false,因為onerror/onload
將被異步調用,因此您可以立即返回image_url
。
編輯
因此事實證明,您將必須像這樣調用該方法:
ng-src="{{checkImageAvailable(entity.thumbnail[0])}}"
但是存在一個問題,因為angular一直在循環調用該方法。 即使您這樣做:
ng-src="{{::checkImageAvailable(entity.thumbnail[0])}}"
它仍然被調用3次。 我不知道為什么3。
因此,在這一點上,我將嘗試使用另一種方法:自定義指令。 初始化時,將圖像設置為隱藏,將onload / onerror處理程序附加到該元素,然后根據調用哪個對象來顯示或不顯示圖像。
讓我知道這是否沒有道理。 演示: http : //jsbin.com/yenipodimi/1/edit?html,js,輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.