Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Ionic Cordova - Default Image Source Directive

Using some combination of Angular / Ionic / Cordova how can I dynamically set the image source to default if request image doesn't exist. NOTE: I know this can be done with an OnError directive, however this results in a temporary question mark image which I would like to avoid. Perhaps making a Cordova File call?

<img ng-src="{{employee.id}}.jpg" df-img-src="default.jpg"/>

Taking things one step further, what about dealing with unknown file extensions. Say if the employee picture can end in either gif, png, jpg, or jpeg, and I would want to set the image-src to which ever one exists on the file system.

like image 720
vicsz Avatar asked Feb 12 '23 23:02

vicsz


1 Answers

Use this Directive.

app.directive('fallbackSrc', function () {
    return{
        link: function postLink(scope, element, attrs) {
            element.bind('error', function () {
                angular.element(this).attr("src", attrs.fallbackSrc);
            });
        }
    }
});

Usage:

<img ng-src="{{employee.id}}.jpg" fall-back-src="default.jpg"/>

Else create a directive for actual source like below

app.directive('actualSrc', function () {
    return{
        link: function postLink(scope, element, attrs) {
            attrs.$observe('actualSrc', function(newVal, oldVal){
                 if(newVal != undefined){
                     var img = new Image();
                     img.src = attrs.actualSrc;
                     angular.element(img).bind('load', function () {
                         element.attr("src", attrs.actualSrc);
                     });
                 }
            });

        }
    }
});

Usage:

<img actual-src="{{employee.id}}.jpg" ng-src="default.jpg"/>

Pluker

like image 165
Subash Selvaraj Avatar answered Feb 16 '23 12:02

Subash Selvaraj