Thursday, 4 February 2016

ng image is image not exist, AngularJS ng-src condition if Not Found (via url)




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


myApp.directive('checkImage', function($http) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            attrs.$observe('ngSrc', function(ngSrc) {
                $http.get(ngSrc).success(function(){
                    alert('image exist');
                }).error(function(){
                    alert('image not exist');
                    element.attr('src', '/images/default_user.jpg'); // set default image
                });
            });
        }
    };
});


1 comment: