简体   繁体   中英

Looping through elements with AngularJS

I have created a slideshow app using AngularJS that uses Instagram photos filtered by a specific tag. Here is the demo and the GitHub repo .

What is the most efficient way of looping through those images according to the principles of AngularJS?

Currently I use a $timeout which moves the first element to the bottom of the images array in combination with CSS which hides every other image except the first one:

$scope.images = [
    'image-001.jpg',
    'image-002.jpg',
    'image-003.jpg'
];

$timeout( function advanceSlide() {
    $scope.images.push( $scope.images.shift() );
    $timeout( advanceSlide, 6000 );
);

Demo : http://jsfiddle.net/YruT6/1/

The other option would be to walk the photos object and apply an active class, like illustrated here . Would that be less resource intensive?

Your solution works OK but using a repeater might not be the best strategy as:

  • all the images will be in the DOM all the time
  • using a repeater and manipulating an array will result in a the repeater re-calculation and DOM reshuffle.

So, for a bigger slideshow you would have many elements in the DOM and frequent / slow DOM manipulations. I could propose an alternative approach:

$scope.imgIndex = 0;
$timeout(function advanceSlide() {
    $scope.imgIndex = ($scope.imgIndex + 1) % $scope.images.length; 
    $timeout(advanceSlide, 1000);
});

and then in a template:

<div ng-app ng-controller="slideshow">
    <img ng-src="{{images[imgIndex].src}}">
</div>​

Here is a jsFiddle: http://jsfiddle.net/ThmeZ/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM