Created
January 10, 2016 02:21
-
-
Save dprea/1cd27241db661818e509 to your computer and use it in GitHub Desktop.
Angular ng-src onerror such as image resolves to a broken src
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* First is the Angular Directive method of solving. | |
* Second is the inline onerror fix that results in a default image. | |
* SOURCE: http://stackoverflow.com/questions/27549134/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"/> | |
// Angular inline onerror fix that results in a default image. | |
<img ng-src="{{ yourImageCurrentScopeVar }}" onerror="this.src='img/default-image-when-occur-a-error.png'"/> | |
I needed to load an image potentially from two different folders, if it did not exist in the first folder, then angular would look for that same image in the second folder. Simple directive and very helpful. Thanks for sharing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good solution.