Show a loading screen as background images load in ng-repeat

老子叫甜甜 提交于 2019-12-06 15:24:17

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!