仅当图像存在于Angular

时间:2016-04-29 14:34:30

标签: javascript html angularjs image

我有两个兄弟元素。一个是图像,另一个是div。如果图像存在,我想显示图像元素,如果图像不存在,则显示div元素。我的元素看起来像

 <img ng-show="product.img" ng-src="{{product.img}}" />
 <div class="left margin-right-1 line-height-15" ng-hide="product.img">{{product.img}}</div>

product.img会产生类似/assets/images/prod.jpg的内容。由于这是一个字符串,因此ng-show将始终为true,并且将显示图像标记。因此,如果图像不存在,它将显示为损坏的图像。基本上我想要的是如果图像不存在,图像标签隐藏和div显示,反之亦然。

我尝试过像

这样的javascript函数
 $scope.imageExists = function(src) {
  var image = new Image();
  image.src = src;
  if (image.width == 0) {
      return false;
  } else {
      return true;
  }
}

并更改了我的图片标记

 <img ng-show="product.img" ng-src="{{imageExists(product.img)}}" />

但这非常昂贵。我每页有100个产品,当它遍历所有图像时,页面变得非常慢。

如果图像存在与否,任何身体都可以指导我在角度显示和隐藏图像元素的最佳方式。

3 个答案:

答案 0 :(得分:3)

在图片中使用onError事件来停用ng-show

中使用的变量
<img ng-show="product.img" ng-src="{{product.img}}" onError="angular.element(this).scope().product.img = false"/>

答案 1 :(得分:1)

您可以使用自定义指令完成此操作。请参阅Plunker:http://plnkr.co/edit/yBb0rNiXIaO4EGTqCAmm?p=preview

您需要在每张图片上附加is404

for(var i = 0; i < products.length; ++i) {
    products[i].image.is404 = false;
}

然后显示它们。您需要将$index作为索引属性传递,以便在指令中使用它。

<img ng-if="!image.is404" on-src-error index="{{$index}}" src="{{image.image}}" />
<div ng-if="image.is404">Uh oh!  Image 404'd.</div>

自定义指令:

app.directive("onSrcError", function() {
  return {
    link: function(scope, element, attrs) {
     element.bind('error', function() {
       //set 404 to true and apply the scope
       scope.images[attrs.index].is404 = true;
       scope.$apply();
     });
    }
  };
});

答案 2 :(得分:0)

上述解决方案很好。但我建议您将onError事件逻辑放在指令中,并使用ng-if来控制可见性。

&#13;
&#13;
var myApp = angular.module('myApp', [])

.directive('img', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '='
    },
    link: function(scope, element, attrs) {
      element.bind('error', function() {
        scope.ngModel.shown = false;
        scope.$apply();
      });
    }
  }
})

.controller('MyController', function($scope) {
  $scope.images = [];
  for (var i = 0; i < 10; i++) {
    if (i == 5) {
      $scope.images[i] = {
        url: 'http://www.notfound.com.fr/404.png'
      };
      continue;
    }
    $scope.images.push({
      url: 'https://unsplash.it/50/50/?random=' + i
    });
  }
});
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
  <title></title>
</head>

<body ng-app="myApp" class="ng-scope">
  <div ng-controller="MyController">
    <div ng-repeat="image in images" ng-init="image.shown=true">
      <p ng-if="!image.shown">
        Empty image here...
      </p>
      <img ng-model="image" ng-if="image.shown" ng-src="{{ image.url }}">
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;