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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With