0

I'm new to AJS so this maybe sound silly but i want to know how to avoid broken image when the image URL coming from an expression or from user input. maybe this explains :

<html ng-app>
<head>

</head>

<body>

Name :<input type="text" ng-model="batman" />

<img ng-src="{{batman}}.png" />


<script src="script/angular.min.js"></script>
</body>
</html>

now i have few pics in that folder and i want when i type it in text bar they appears on the page. but we always have this broken image showing until we didn't type the exact image name. so is there any way to avoid the broken image to show up. thanks

coljadu
  • 11
  • 1
  • 3

2 Answers2

1
<div ng-if="batman">
    <img ng-src="{{batman}}.png" />
</div>

If batman model does exist, then only this div will render

Vamsi
  • 9,510
  • 6
  • 38
  • 46
0

Here's a directive that hides the image element when the value of ngSrc is changed until it sees the 'load' event, then it displays the element (plunker):

app.directive('hideUntilGood', function() {
  return {
    restrict: 'A',
    multiElement: true,
    link: function(scope, element, attrs) {
      attrs.$observe('ngSrc', function (value) {
        // fix where ngSrc doesn't update when blank
        if (!value || value.length == 0) {
          element.attr('src', value);
        }
        element.css("display", "none");
      });
      element.bind('load', function() {
        element.css("display", "");
      });
    }
  };

})

Usage:

<img hide-until-good ng-src="{{batman}}.png">
Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113