[英]How to check remote image exists in angularjs?
下面是代碼:
<div ng-repeat="u in users">
<!--I will always receive a URL -->
<div ng-if="u.imageUrl"> <!--Here I want to check if the provided URL is active-->
<!--Only seen if image url is live and active -->
</div>
<div>
<!--do some other things-->
</div>
</div>
例如: http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png
: http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png
是活動 URL 但http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder11.png
不是。 隨着登錄的增加, users
也可能有很多記錄。
你可以用一個指令來做到這一點:
這是JSFiddle
JS:
.directive('userAvatar', function() {
return {
link: function(scope, element, attrs) {
var placeholder = 'path/to/your/placeholder.jpg';
scope.$watch(function() {
return attrs.ngSrc;
}, function (value) {
if (!value) {
element.attr('src', placeholder);
}
});
element.bind('error', function() {
element.attr('src', placeholder);
});
}
};
});
HTML:
<div ng-repeat="u in users">
<div>
<img ng-src="{{u.imageUrl}}" user-avatar />
</div>
<div>
所以現在如果ng-src
值是一個 404 not found 圖像,它將被默認placeholder
替換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.