在 ng-repeat 中加载背景图像时显示加载屏幕 [英] Show a loading screen as background images load in ng-repeat

查看:29
本文介绍了在 ng-repeat 中加载背景图像时显示加载屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 ng-repeat 加载的列表,其中每个元素都包含一个 img 标签.我想显示某种加载指示器(遮挡列表项),直到每个项目中的每个图像都完成加载.

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.

我想我需要通过 angular back-img 指令连接一些事件广播,但我真的不知道从哪里开始.

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.

推荐答案

好的,我解决了我的问题.首先,@Vladimir,你说得对——back-img 是我同事写的一个指令,它让我暂时无法解决问题.

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.

我所做的是编写一个非常简单的指令,在 imgload 事件上调用一个 $scope 绑定函数.我的控制器计算已加载的图像数量,一旦加载了足够多的图像,它就会删除加载指示器并显示图像列表.以下是代码摘要:

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:

我的指令:

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);
            });
        }
    }
});

在元素内:

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

最后,在控制器中:

$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!

这篇关于在 ng-repeat 中加载背景图像时显示加载屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆