0

I'm new with angular, i was creating an app with where you can search a character while typing in input box. now while typing the name let say "superman" , you will see a broken images until you type the complete name, once you type the full name "superman" you will the images otherwise just broken images.

I read that using ng-src will solve this issue, but its also not working, here is my code and im using crome.

<!doctype html>
<html>
<head>
    <title> Project Zippy</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

</head>
<body>
    <header>
        <h1> Zippy...</h1>
    </header>
    <section>
        <div ng-app="">
            <input type="text" ng-model="superhero"><br />
            <img ng-src="images/{{superhero}}_tn.png">

        </div>
    </section>
    <script src="script/angular.min.js"></script>
    <script src="script/angular-route.min.js"></script>

</body>
</html>
coljadu
  • 11
  • 1
  • 3
  • `ng-src` will help, given that the whole url, once it is interpolated, is *valid*, but it won't magically know that the url is not valid – JoseM Nov 25 '14 at 17:24
  • but isn't there any way to hide that broken image and show it only if that is correct url for images ? – coljadu Nov 25 '14 at 17:37
  • A similar problem was solved [on this stackoverflow question](http://stackoverflow.com/questions/16310298/if-a-ngsrc-path-resolves-to-a-404-is-there-a-way-to-fallback-to-a-default#) – Cengkuru Michael Jan 30 '17 at 11:41

1 Answers1

4

You can use this directive:

app.directive('onError', function() {
  return {
    restrict:'A',
    link: function(scope, element, attr) {
      element.on('error', function() {
        element.attr('src', attr.onError);
      })
    }
  }
})

Example:

<img ng-src="{{url}}" on-error="http://rationalwiki.org/w/images/f/f5/Error_icon.svg" />

Working example: http://plnkr.co/edit/avGEDb?p=preview

but put transparent 1x1 image for error image url.

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59