javascript - Passing object from array model into directive -
i have array of objects containing images source links. want add flag each image when source link dead , image can not loaded. , have following html code , directive.
problem can't pass image object directly directive set property on it. i've tried adding scope directive , passing parameter didn't work, ended ugly approach tighly coupling directive outside scope , working on (annotated lines in directive source fragment).
question is: implemented in more elegant way passing image object directive , without manual $apply() call? yes, i've tried during weekend , 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 , 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; // problematic scope.$apply(); // problematic }); } };
try:
.directive('fallbacksrc', function() { return { restrict: 'a', link: function(scope,element,attrs){ element.on('load', function() { //loaded }); element.on('error', function() { element.attr('src',attrs.fallbacksrc); }); scope.$watch('ngsrc', function() { //start }); } } })
try:
ng-repeat="image in images" ng-init="image.errorpresent = false"
Comments
Post a Comment