【问题标题】:How to check remote image exists in angularjs?如何检查angularjs中是否存在远程图像?
【发布时间】:2016-07-09 00:15:13
【问题描述】:

下面是代码:

<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 不是。 随着登录次数的增加,users 也可能有很多记录。

【问题讨论】:

  • angular-img-fallback 这可能是您正在寻找的东西吗?
  • 如果我是正确的 angular-image-fallback 用于显示替代图像。但我直接不想显示那个 div。
  • 我知道ng-src。但是如果我想隐藏我的 div 呢?
  • 不知道这是否可行,但可能会退回到 1x1 像素图像?

标签: javascript angularjs image


【解决方案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 not found 图像,它将被默认的 placeholder 替换

【讨论】:

  • 谢谢,但我已经知道了。我不想要任何替代图像。你可以检查我的问题,如果u.imageUrl 中的 URL 无效或找不到,我希望隐藏我的div
猜你喜欢
  • 2012-05-16
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 2013-04-30
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多