Last active
August 29, 2015 14:20
-
-
Save aivascu/a679fd02b9fb781a0d7d to your computer and use it in GitHub Desktop.
AngularJS directive that shows a placeholder image, using HolderJS, when the image request yielded an error.
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
// Usage: <img ng-src="{{imageurl || '//:0'}}" ng-fallback="holder.js/210x140/text:No Image" /> | |
'use strict'; | |
(function(angular, Holder){ | |
var fallbackDirective = function () { | |
return { | |
link: function (scope, element, attrs) { | |
element.bind('error', function () { | |
if (attrs.src !== attrs.ngHolder && Holder != null) { | |
var src = null; | |
if (attrs && attrs.ngHolder && attrs.ngHolder.split) { | |
var attributes = attrs.ngHolder.split('.'); | |
var prop = scope; | |
for (var i = 0; i < attributes.length; i++) { | |
if (prop[attributes[i]]) { | |
prop = prop[attributes[i]]; | |
} else { | |
prop = attrs.ngHolder; | |
break; | |
} | |
} | |
src = prop; | |
} | |
attrs.$set('src', src); | |
Holder.run({ images: element[0], nocss: true }); | |
} else { | |
console.error(attrs, Holder); | |
} | |
}); | |
} | |
}; | |
} | |
angular.module('app').directive('ngFallback', fallbackDirective); | |
}(angular, Holder)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment