Reputation: 41
I have this code, which uses url's from json file, but sometimes no photos are available and I need to place "NO IMAGE" instead. I tried "onerror" and "fallback-src", but without any success. Could you suggest something, please?
<ion-item ng-repeat="item in artists.programmeField" class="item item-thumbnail-left">
<img ng-src="URL/{{item._photos[0]._id}}.jpg" fallback-src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/2000px-No_image_available.svg.png" class="padding-vertical">
<p>{{item.startField.slice(8,10) + ":" + item.startField.slice(10,12)}}</p>
<h2>{{item.titleField[0].valueField}}</h2>
<p>{{item.descField[0].valueField}}</p>
</ion-item>
Upvotes: 2
Views: 604
Reputation: 7954
var app = angular.module("MyApp", []);
app.controller("MyCtrl", function($scope) {
$scope.ngSrc = "http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png";
$scope.errSrc = "https://developers.google.com/games/services/images/branding/ic_play_games_badge_green.png";
});
app.directive('errSrc', function() {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
if (attrs.src != attrs.errSrc) {
attrs.$set('src', attrs.errSrc);
}
});
attrs.$observe('ngSrc', function(value) {
if (!value && attrs.errSrc) {
attrs.$set('src', attrs.errSrc);
}
});
}
}
});
/* Styles go here */
label {
display: inline-block;
width: 75px;
}
input {
width: 600px;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyCtrl">
<h2>Blank ngSrc</h2>
<img ng-src="" err-SRC="http://google.com/favicon.ico" />
<h2>Image doesn't exist</h2>
<img ng-src="smiley.png" err-SRC="smiley2" />
</body>
</html>
Create a directve errSrc
directive
var app = angular.module("MyApp", []);
app.directive('errSrc', function() {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
if (attrs.src != attrs.errSrc) {
attrs.$set('src', attrs.errSrc);
}
});
}
}
});
html
<img ng-src="URL/{{item._photos[0]._id}}.jpg" err-src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/2000px-No_image_available.svg.png" class="padding-vertical">
Upvotes: 1