I am porting a bunch of images that I stored locally to an online resource that stays up to date. Originally when I stored the images locally I could use the following condition for my images.
<img ng-src="/Content/champions/{{Champions1[champ1-1].cName.trim() || 'None'}}.png"
This would grab the current image pathway based off a name, and if it did not exist it would simply return the image path of /Content/champions/None.png
I figured this would work the same way via a url. So I made the syntax.
<img ng-src="http://ddragon.leagueoflegends.com/cdn/4.20.1/img/champion/{{Champions1[champ1-1].cName.trim()
||
'/Content/champions/None'}}.png"
What I assumed would occur, is that if the above URL returned 404 (Not Found)
, it would default back to my local storage for the None image. However, it still tries to display an online image and shows the "broken image/picture" icon rather than conditioning over the to my local "None" image.
How might I fix this? Or why is Angular not responding correctly to this scenario when it is saying Not Found 404 (Not Found)
?
Sometimes it tries to add the conditioned syntax to the URL rather than re-looking in the home directory, could that be the problem? i.e. It sometimes returns the following rather than restarting from my Content folder. http://ddragon.leagueoflegends.com/cdn/4.20.1/img/champion//Content/champions/None.png
{{Champions1[champ1-1].cName || 'None'}}
This construction would replace your image name with 'None'
only when your image is null or undefined.
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="http://google.com/favicon.ico"/>
See example on JSFiddle
Other simple solution is use the following code, that perform the same final result:
<img ng-src="{{ yourImageCurrentScopeVar }}" onerror="this.src='img/default-image-when-occur-a-error.png'"/>
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