在每次迭代后永不结束 AngularJS + setTimeout 中的数组循环

Never ending loop through array in AngularJS + setTimeout after each iteration

如何在 AngularJS 中实现永无止境的循环?

我的尝试:

item_list = [{'id':1, 'photo':'path/src'}, {'id':2, 'photo':'path/src'}, {'id':3, 'photo':'path/src'}];

item_list.map(function(item) {
    setTimeout( function () {
         setCoverImage(item.photo);
    }, 5000);
)

我将使用 setCoverImage() 每 5 秒使用来自 item_list 的数据更改封面图像。

像这样使用 AngularJS 的 $interval 服务:

$interval( function () {
     setCoverImage(item.photo);
}, 5000);

在你的 controller/service 中注入 $interval 服务(随便),然后你可以使用这样的东西:

 let currentPhotoIdx = 0;
 const maxAvailablePhotoIdx = item_list.length - 1;
 $interval(() => {
    setCoverImage(item.photo[currentPhotoIdx]);
    currentPhotoIdx === maxAvailablePhotoIdx ? currentPhotoIdx = 0 : currentPhotoIdx++;
 }, 5000);

$interval 的替代解决方案是 $timeout:

function setCoverImageLoop(photo) {
    $timeout(function () {
        setCoverImage(photo);
        setCoverImageLoop(photo);
    }, 5000);
}

item_list = [{'id':1, 'photo':'path/src'}, {'id':2, 'photo':'path/src'}, {'id':3, 'photo':'path/src'}];

item_list.map(function(item) {
     setCoverImageLoop(item.photo);
});

这可能有点old-school,主要针对喜欢来自setTimeout的人。

首先,您应该使用 AngularJS 的 $interval. Then simply increment a counter and use it to access the current element's photo property in your controller and use ng-src 在您的 img 标签中反映 URL。

<img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}">

请注意,切勿为计数器分配与数组中的元素不对应的值。

if ((that.currentIndex + 1) >= that.item_list.length)

查看下面的完整示例

angular.module('appModule', []).controller('MyController', ['$scope', '$interval', function($scope, $interval) {
  this.item_list = [{
    'id': 1,
    'photo': 'https://i.pinimg.com/736x/32/76/a2/3276a2111c65b2131ef834736f47162b--birthday-kitten-birthday-hats.jpg'
  }, {
    'id': 2,
    'photo': 'http://img.playbuzz.com/image/upload/f_auto,fl_lossy,q_auto/cdn/154cb38e-55e3-4294-bffe-6906b6a41a6b/c33bcc8b-40be-49c9-bad1-ee85f8275189.jpg'
  }, {
    'id': 3,
    'photo': 'http://4.bp.blogspot.com/-J4ioK5aRks8/Tx8d9D5K54I/AAAAAAAAABM/iTL4sbsNYmc/w1200-h630-p-k-no-nu/Surprised+and+serious+kitten.jpg'
  }];
  var that = this;
  this.currentIndex = 0;
  $interval(function() {
    if ((that.currentIndex + 1) >= that.item_list.length) {
      that.currentIndex = 0;
    } else {
      that.currentIndex++;
    }
  }, 5000);
}])

angular.bootstrap(window.document, ['appModule'], {
  strictDi: true
});
<div ng-controller="MyController as myCtrl">
  <img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>