2

I would love to loop through the following array in my controller,

var array = ['text1', 'text2', 'text3'];

Then display an item at a time in my view using angular $interval.

When it gets to the last item, it should start again from item 1. Only one item should be displayed at a time.

Please don't judge, sounds easy but this is my 2nd week or so with angularjs.

3
  • It's a basic carousel - just have to think through it. You need an activeItem to denote which item is currently being displayed - and each interval, check the index of the active item and go to the next. If you're at the last index, start at the beginning. Commented Aug 5, 2016 at 12:47
  • any example for a start? Commented Aug 5, 2016 at 12:54
  • 1
    Possible duplicate of How do you rotate text values in Angular? Commented Aug 5, 2016 at 12:59

1 Answer 1

3

Updated answer according to @Nicholas Robinson and @4castle suggestion on the comments:

angular
    .module('MyApp', [])
    .controller('MyController', function($scope, $interval) {
        $scope.array = ['text1', 'text2', 'text3'];

        $scope.showedItem = 0;

        $interval(function() {
            $scope.showedItem = ++$scope.showedItem % $scope.array.length;
        }, 1000);
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp" ng-controller="MyController">
    <!-- <p ng-repeat="item in array" ng-show="showedItem === $index">{{item}}</p> -->
    <!-- Improvements without the need of ng-repeat and ng-show -->
    <p>{{ array[showedItem] }}</p>
</div>

Updated answer according to @Nicholas Robinson and @4castle suggestion on the comments.

Sign up to request clarification or add additional context in comments.

2 Comments

Instead of $scope.showedItem++; if ($scope.showedItem > $scope.array.length){$scope.showedItem = 0;} you can just use $scope.showedItem = ++$scope.showedItem % $scope.array.length - Works the same
You don't need ng-repeat or ng-show. Just bind to {{ array[showedItem] }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.