I have an array of objects containing images with source links. I want to add flag to each image when source link is dead and image can not be loaded. And I have following html code and directive.
Problem is that I can't pass image object directly to the directive to set property on it. I've tried with adding scope to the directive and passing by parameter but it didn't work, so I ended with this ugly approach with tighly coupling directive with outside scope and working on it (annotated lines in the directive source fragment).
Question is: Could it be implemented in a more elegant way by passing image object to directive and without manual $apply() call? Probably yes, but I've tried during weekend and failed.
<!-- AngularJS v. 1.0.8 -->
<ul>
<li ng-repeat="image in images">
<div>
<img ng-src="{{image.srcLarge}}" fallback-src="/assets/fallback.png"/>
<!--- image comments and other data -->
</div>
</li>
<ul>
Directive:
.directive('fallbackSrc', function () {
var fallbackSrc = {
restrict: 'A',
link: function postLink(scope, iElement, iAttrs) {
iElement.bind('error', function() {
console.log("directive");
angular.element(this).attr("src", iAttrs.fallbackSrc);
scope.image.errorPresent = true; // this is problematic
scope.$apply(); // this is also problematic
});
}
};