0

I want to replace all broken img url with a default when the broken url does not exists with AngularJS jqlite attr(). I use it like this but won't work.

var app = angular.module('app');

app.controller('AdminCtrl',function($scope{
    angular.element(document.querySelector('img')).attr("onerror","this.src='../assets/img/broken/broken-link.png'");
})

What is correct script?

Ehsan Ali
  • 1,362
  • 5
  • 25
  • 51

2 Answers2

1

You have libraries that already do that.

Check angular-fallback-src and angular-img-fallback.

Ygalbel
  • 5,214
  • 1
  • 24
  • 32
1

there are few ways to solve that

try the next options

myApp.directive('onErrorSrc', function() {
     return {
         link: function(scope, element, attrs) {
           element.bind('error', function() {
              if (attrs.src != attrs.onErrorSrc) {
                attrs.$set('src', attrs.onErrorSrc);
              }
           });
         }
     }
  });

<img ng-src="wrongUrl.png" on-error-src="someurl.png"/>

Or

<img ng-src="{{ imagesrc}}" onerror="this.src='someimgsrc.png'"/>

as you dont want to use directive you can use this img tag line will make the work for you

to do it dynamicly

<img ng-src="{{ imagesrc}}" nerror="angular.element(this).scope().imgError()"/>

and implement this src on the function or scope var

check this plnkr https://plnkr.co/edit/S6KDo2crjMGASKtrToGo?p=preview

Erez
  • 574
  • 1
  • 6
  • 23