如何在范围数组中一次显示一个项目?
我尝试了几种变体,但无论哪种方式,范围内的所有项目都会立即出现。理想情况下,我希望在给定时间内显示范围中的一个项目,然后转到下一个项目。
var str = "[{property1: 'value1'} , {property1: 'value2'}]";
var array = str.replace("[","").replace("]","").split(",");
我使用THIS篇文章进行了几次建模。我甚至可以使用setInterval来使用它,但因为使用angular应该只使用$ interval。
由于
答案 0 :(得分:3)
这是我将如何做到的。这样做你想要的吗?
angular.module('app', []).controller('MyController', function($scope, $interval) {
var items = [{
name: "example 1",
title: "example title 1"
}, {
name: "example 2",
title: "example title 2"
}, {
name: "example 3",
title: "example title 3"
}];
$scope.start = function() {
$scope.currentItem = items[0];
$scope.currentIndex = 1;
$interval(function() {
$scope.currentItem = items[$scope.currentIndex];
$scope.currentIndex++;
if ($scope.currentIndex >= items.length) {
$scope.currentIndex = 0;
}
}, 1000);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<button ng-click="start()">Start</button>
<br/>Name: {{currentItem.name}}
<br/>Title: {{currentItem.title}}
</div>
</div>
答案 1 :(得分:2)
您需要将当前索引存储在$interval
回调之外,如下所示:
var current = -1;
var handle = null;
$scope.start = function () {
var items = [
{ name: "example 1", title: "example title 1"},
{ name: "example 2", title: "example title 2"},
{ name: "example 3", title: "example title 3"}
];
handle = $interval(function () {
current = (current + 1) % items.length;
$scope.item = items[current];
}, 3000);
}
$scope.stop = function(){
$interval.cancel(handle);
}
答案 2 :(得分:1)
function intervalCtrl($scope, $interval) {
$scope.start = function() {
var items = [
{ name: "example 1", title: "example title 1"},
{ name: "example 2", title: "example title 2"},
{ name: "example 3", title: "example title 3"}
];
var i = 0;
$scope.items = items[i];
$interval( function () {
i++;
$scope.items = items[i];
}, 3000,items.length);
}
}
$interval
函数将被调用items.length
次。
这样可行。