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

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

例如: http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png 是有效的 URL 但 http://www.pacinno.eu/wp- content/uploads/2014/05/placeholder11.png 不是。 此外,随着登录的增加,用户 可能会有很多记录。

最佳答案

您可以使用指令来做到这一点:

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

关于javascript - 如何检查angularjs中是否存在远程图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36148805/

相关文章:

jquery - 仅当用户禁用 javascript 时才显示背景

javascript - 如何停止 Javascript 中的循环函数

java - 如何更好地将丰富的字符串内容和图像保存到数据库中?

angularjs - Angular $location.path 没有按预期工作

c# - 如何使用 AngularJS 构建我的 MVC Web API 应用程序而不产生命名冲突

CSS 将全屏图像与最大高度对齐到中间

HTML, CSS - 图像中的图像,怎么做?

javascript - rails 5 : Trying to render divs with a single partial but keep the div class unique so that JQuery doesn't fire on all partials

javascript - onClick 未在子 div 上调用

javascript - 类型错误 : Object doesn't support this action in IE 11