等到图像加载到angularjs工厂中

Wait till images are loaded inside angularjs factory

本文关键字:工厂 angularjs 加载 图像      更新时间:2023-09-26

我创建了一个小功能,允许用户搜索电影标题。这会从 tmdb.org 执行 JSON 请求,该请求返回标题、日期和 url 的海报等内容。

控制器:

    angular.module('movieSeat')
        .factory('moviesearchFactory', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {
            var factory = {};
            function httpPromise(url) {
                var deferred = $q.defer();
                $http({
                    method: 'JSONP',
                    url: url
                })
                    .success(function (data) {
                        deferred.resolve(data.results);
                    })
                    .error(function () {
                        deferred.reject();
                    });
                return deferred.promise;
            }
            factory.getMovies = function (searchquery) {
                return httpPromise('http://api.themoviedb.org/3/' + 'search/movie?api_key=a8f7039633f2065942cd8a28d7cadad4' + '&query=' + encodeURIComponent(searchquery) + '&callback=JSON_CALLBACK')
            }
            return factory;
        }]);

工厂:

    angular.module('movieSeat')
        .controller('moviesearchCtrl', ['$scope', 'moviesearchFactory', function ($scope, moviesearchFactory) {
            $scope.createList = function (searchquery) {
                $scope.loading = true;
                moviesearchFactory.getMovies(searchquery)
                    .then(function (response) {
                        $scope.movies = response;
                    })
                    .finally(function () {
                        $scope.loading = false;
                    });
            }
        }]);

模板:

    <div ng-controller="moviesearchCtrl" id="movieSearch">
        <div class="spinner" ng-show="loading">Loading</div>
        <input ng-model="searchquery" ng-change="createList(searchquery)" ng-model-options="{ debounce: 500 }" />
        {{ search }}
        <ul>
            <li ng-if="movie.poster_path" ng-repeat="movie in movies | orderBy:'-release_date'">
                <span class="title">{{ movie.title }}</span>
                <span class="release_date">{{ movie.release_date }}</span>
                <img ng-src="https://image.tmdb.org/t/p/w300_and_h450_bestv2/{{ movie.poster_path }}" class="poster"/>
            </li>
        </ul>
    </div>

此功能的问题在于微调器类仅等待请求的数据。但是仅仅加载一些 JSON 并不需要很长时间,它会从浏览器中的 api 下载图像,这需要一段时间。

这会导致两件事。在浏览器中呈现图像之前,首先删除微调器,并且由于图像都是异步加载的,因此会导致瀑布效果。

解决此问题的最简单方法是延迟控制器中的.then调用,直到为用户下载映像,然后进入.finally调用。

但是我找不到一种方法来创建这样的东西。有什么提示吗?

试试这个,让我知道:

这个想法是使用指令发出渲染完成事件:

dashboard.directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

在控制器中保留等待图像加载承诺的事件侦听器:

    $scope.$on('dataLoaded', function(ngRepeatFinishedEvent) {
        // your code to check whether images has loaded
        var promises = [];
        var imageList = $('#my_tenants img');
        for(var i = 0; i < imageList.length; i++) {
            promises.push(imageList[i].on('load', function() {}););
        }
        $q.all(promises).then(function(){
            // all images finished loading now
            $scope.loading = false;
        });
    });

在 HTML 端:

<div id = "my_tenants">
    <div ng-repeat="tenant in tenants" on-finish-render="dataLoaded">
        // more divs
    </div>
</div>