Show a loading screen as background images load in

2019-05-22 15:52发布

I have a list loaded through ng-repeat where each element contains an img tag. I'd like to show some sort of loading indicator (occluding the list items) until every image within every item has finished loading.

I guess I would need to hook into some event broadcast by the angular back-img directive but I don't really know where to start here.

2条回答
放荡不羁爱自由
2楼-- · 2019-05-22 16:35

Okay, so I solved my problem. First of all, @Vladimir, you're totally right -- back-img was a directive my colleague wrote, which obscured the solution to me for a while.

What I've done is write a really simple directive that calls a $scope-bound function on the img's load event. My controller counts the number of images that have loaded, and once enough images have loaded, it removes the loading indicator and shows the list of images. Here's a summary of the code:

My directive:

app.directive('loadedImage', function($parse) {
return {
    restrict: 'A',
    scope: true,
    link: function(scope, element, attrs) {
        element.bind("load", function(event) {
            var invoker = $parse(attrs.loadedCallback);
            invoker(scope);
            });
        }
    }
});

Within the element:

<img ng-src='{{ item.large }}' loaded-image loaded-callback="imageLoaded(r.id)">

And finally, within the controller:

$scope.numLoaded = 0;
$scope.showLoading = true;
$scope.showImages = false;

$scope.imageLoaded = function(id) {
    $scope.numLoaded++;
    if ($scope.numLoaded > 9) {
        $scope.showLoading = false;
        $timeout(function() {
            $scope.showImages = true;
        }, 500) //show images once loading indicator has faded away
    };
};

I'm not sure this is the right approach, but it reliably works for me!

查看更多
男人必须洒脱
3楼-- · 2019-05-22 16:47

I am not aware of any back-img directive, but image loading is asynchronous and you cant generally guarantee that your 3rd image will load before your 8th image.

WHat I would do is add an 'onload' listener to every img tag that gets added by ng-repeat and simply figure out when all of your images have loaded by keeping count of 'onload' hits and comparing it against the total number of images.

This is essentially what https://github.com/desandro/imagesloaded does, but in the jquery-land.

查看更多
登录 后发表回答