簡體   English   中英

如何檢查angularjs中是否存在遠程圖像?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM