Search code examples
angularjsangularjs-directivesrcfallback

Create a nested fallback src for an Image using angularjs directive


In my tag if the src returns a 404 then I can display a fallback image using directives, but if this fallback image is also returns 404 the how can I show another image using directive


Solution

  • Create a directive to go through a series of error images and provide them one after the other.

    You can provide alternative image urls in the tag itself.

    <img fallbacksrc="http://url1/error.jpg,http://url2/error.jpg" src="http://url0.image.jpg">
    

    Then write a directive for fallbacksrc and bind the tag for error event. Use split function to alternative images in to an array. You can then choose from this array inside the link function.

    The information you are looking for is that the error event will occur any number of times as long as the src fails. So there is no limit for this to occur if all the images you are setting inside the directive fails continuously.

    Here is a sample code. I'm using an array of error images in the scope itself in this example without providing them inside the tag.

    function MyCtrl($scope) {
    
           $scope.image = "http://greentreesarborcareinc.com/wp-content/uploads/2014/01/image-placeholder.jpg1"
    
            $scope.errorImageIdx = 0;
            $scope.errorImages = ["http://spanning.com/assets/uploads/images/11954453151817762013molumen_red_square_error_warning_icon.svg_.med_.png", "http://fivera.net/wp-content/uploads/2014/03/error_z0my4n.png"]
        }
    
    
    
    
    myApp.directive('fallbacksrc', function() {
    
        return {
        link: function(scope, ele) {       
    
            ele.bind('error', function() {            
    
                if (scope.errorImageIdx <= scope.errorImages.length - 1) {                    
                    angular.element(this).attr("src", scope.errorImages[scope.errorImageIdx]);
                    scope.errorImageIdx++;
                }    
          });
        }
       }  
    
    });
    

    Here the tag will try to display the image referenced in $scope.image. But that is invalid. So, it tries to load the images from the array.

    Try setting the first element of the array to something invalid. It will automatically select the second image in this case.