Obasi Obeny Oj Obasi Obeny Oj - 6 months ago 22
Javascript Question

How to loop through an array in angular controller and display one item at a time

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.


Updated answer according to @Nicholas Robinson suggestion on the comment.

    .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>