如何预加载几张图片& angularJS中的进度条

时间:2016-07-03 17:03:05

标签: javascript html angularjs twitter-bootstrap image-preloader

给定一个数组,其中包含要预加载的几个图像的网址,我想循环每个图像,并且当每个图像都已加载时,上传我在屏幕上显示的Bootstrap的进度条,同时加载图像。 / p>

我试图在我的Controller中循环该数组,在每次迭代时使用.onload()方法执行此操作,但我只将进度条从0%更新为100%;我看不到每个更新步骤(0%... 5%.. 25%......等等)。

这是我的代码的相关部分:

HTML + AngularJS

    <div id="node-002" class="container-fluid node full-height animated fadeIn" ng-controller="node-002">
      <div class="row full-height">
        <div class="col-xs-10 col-xs-offset-1 full-height">
          <p class="text-center text-loading">Loading {{progress}}%</p>
          <div id="progress-bar" class="progress">
            <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: {{progress}}%">
            </div>
          </div>
        </div>
      </div>
    </div>

角度控制器

    var files = [
      '../assets/img/image-1.jpg', 
      '../assets/img/image-2.jpg',
      '../assets/img/image-3.jpg',
      '../assets/img/image-4.jpg',
      '../assets/img/image-5.jpg',
      '../assets/img/image-6.jpg',
      '../assets/img/image-7.jpg',
    ];

    app.controller('node-002', ['$scope', '$http', '$timeout', '$location', function($scope, $http, $timeout, $location) {
      $scope.progress  = 0;
      var filesLoaded  = 0;
      var filesToLoad  = files;
      for (var i = 0; i < filesToLoad.length; i++) {
        var file = document.createElement('img');
        file.src = filesToLoad[i];
        file.style.display = 'hidden';
        file.onload = function() {
          filesLoaded  ++;
          if (filesLoaded  === filesToLoad.length) {
            console.log('Files already loaded');
            $scope.progress = 100;
            // Do some stuff when all files are loaded...
          }
          else {
            console.log((100 * filesLoaded / filesToLoad.length) + '% loaded');
            $scope.progress = 100 * (filesLoaded / filesToLoad.length);
            $scope.$apply(); // Is it mandatory?
          }
        }
        document.getElementById('hidden-data').appendChild(file);
      }
    }]);

使用AngularJS执行此操作的最佳方法是什么? 提前谢谢。

0 个答案:

没有答案