如何检查angularjs中是否存在远程图像

How to check remote image exists in angularjs?

本文关键字:存在 图像 是否 程图像 angularjs 何检查 检查      更新时间:2023-09-26

下面是代码:

<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/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 未找到的图像,它将替换为默认placeholder