Reputation: 795
I have a list of items in some search results, some items have images, others do not. For those those items that do not have images I want to show a placeholder.
What would be the best approach to this? I am currently trying to do it with a function (imageURL) and passing it the image details for the current item in the loop/repeat.
<ion-item ng-repeat="listing in searchResults.listings">
<div class="item item-image">
<img src="{{::searchResults.imageURL(listing._id,listing._source.filename1)}}">
</div>
.....
Inside the controller (controller as SearchResults):
self = this;
.....
self.imageURL = function(listing_id, listing_filename) {
if (angular.isUndefined(listing_id) || angular.isUndefined(listing_filename)) { //No image
return placeholderImage; //We want to show placeholderImage
}
return self.imageURL + listing_id + "/" + listing_filename; //Show the image
};
I will also be using a lazy loader directive at a later point, so will not be using the "src" attribute directly at that time.
Thanks
Upvotes: 1
Views: 1550
Reputation: 4443
I would create a directive that replaces the src
attribute, like ng-src
does, and internally handles the logic you currently have in your imageURL
function.
If the directive is named image-url
then the markup would look something like this:
<img image-url="listing">
And your directive would look something like this:
app.directive('imageUrl', function () {
return {
scope: {
imageUrl: '='
},
link: function (scope, element, attrs) {
var imageUrl;
if (angular.isUndefined(scope.listing._id) || angular.isUndefined(scope.listing._source.filename1)) { //No image
imageUrl = placeholderImage; //We want to show placeholderImage
}
else {
imageUrl = "/" + scope.listing._id + "/" + scope.listing._source.filename1; // Set the src attribute
}
element.attr("src", imageUrl); // Set the src attribute
}
};
});
You really don't want to bind directly to the src
attribute for reasons described in the ngSrc documentation
Upvotes: 1
Reputation: 9806
Use ng-src
rather than src
.
From angular docs;
Using Angular markup like
{{hash}}
in asrc
attribute doesn't work right: The browser will fetch from the URL with the literal text{{hash}}
until Angular replaces the expression inside{{hash}}
. ThengSrc
directive solves this problem.
Upvotes: 0