如何检查angularjs中存在的远程图像?

时间:2016-03-22 07:51:53

标签: javascript angularjs image

以下是代码:

<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>

e.g。 :http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png是有效网址,但http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder11.png不是。 随着登录的增加,users也可能有许多记录。

1 个答案:

答案 0 :(得分:1)

您可以使用指令执行此操作:

以下是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