AngularJS ng-src condition if Not Found (via url)

0
711

Angular directive ngSrc doesn’t have any native features for processing of 404 response.

But it would be fixed with the following onErrorSrc directive.

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

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="https://google.com/favicon.ico"/>

LEAVE A REPLY

Please enter your comment!
Please enter your name here