如何在角度控制器中循环数组并一次显示一个项目

时间:2016-08-05 12:44:04

标签: angularjs

我想在我的控制器中循环遍历以下数组

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

然后使用angular $ interval在我的视图中一次显示一个项目。

当它到达最后一个项目时,它应该从第1项开始。一次只能显示一个项目。

请不要判断,听起来很容易,但这是我第二周左右的角度。

1 个答案:

答案 0 :(得分:3)

根据@Nicholas Robinson和@ 4castle对评论的建议更新了答案:



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>
&#13;
&#13;
&#13;

根据@Nicholas Robinson和@ 4castle关于评论的建议,

更新了答案

相关问题