What I want to do is to display a placeholder image before the real image fully loaded. And I found the answer here. I am using exactly the same code as the accepted answer. This answer works pretty good for normal situation.
However, my case is a little bit different. On my page, I have two tabs. I'm using ion-slide-box
for the tab selection. And I load different content when user switch the tabs. Under each tab, it's a long list of items. Each item has a image, on which I implement this placeholder image display method. User is able to scroll down to see more items. So when user scroll down, I'll load more items.
Here is a peek of my code, it's simplified:
HTML:
<div class="tab-bar">
<div class="tab-option" ng-class="(slide == 0 ? 'active' : '') ng-click="setSlide(0)">
Tab 1
</div>
<div class="tab-option" ng-class="(slide == 1 ? 'active' : '') ng-click="setSlide(1)">
Tab 2
</div>
<ion-view>
<ion-content>
<div class="list">
<ion-slide-box on-slide-changed="slideHasChanged($index)" active-slide="slide">
<ion-slide>
<ion-list ng-repeat="item in items">
My content and Image Here
<img hires="{{item.realImageUrl}}" src="placeholderImage.jpg"/>
</ion-list>
</ion-slide>
<ion-slide>
<ion-list ng-repeat="item in items">
My content and Image Here
<img hires="{{item.realImageUrl}}" src="placeholderImage.jpg"/>
</ion-list>
</ion-slide>
</ion-slide-box>
</div>
</ion-content>
In my controller(this is simplified a lot, I don't want to bother with un-related code):
slideHasChanged = function (index) {
getMoreItems(); //get more data from server here.
};
This is the directive:
app.directive('hires', function() {
return {
restrict: 'A',
scope: { hires: '@' },
link: function(scope, element, attrs) {
console.log('link fired');
element.one('load', function() {
console.log('load fired');
element.attr('src', scope.hires);
});
}
};
});
The issue is, the placeholder image works good for the first time I come to this page and load the first batch of items. But whenever I need to scroll down, or switch tab, the placeholder image doesn't work anymore. The behavior is that, it's always showing placeholder image, the real image is not displayed after it's fully downloaded/loaded.
I wonder is it because this method only works when you load a page? And doesn't work because switching tab or scrolling down doesn't trigger page loading? If I want this to work for my situation, what change is needed on this method?
I put two debugging messages in my directives, I log out 'link fired' and 'load fired'. Turns out that the link function is fired correctly, it's just the element.one('load', function())
is not fired. Is it that the scope somehow doesn't match? Any thoughts?
I've been trying the code a lot. And actually sometimes it works, when I switch tab or scroll down. But most time doesn't work. This is confusing, I don't know why it works sometimes.