我有一个JSON对象,我需要它能够遍历数组中的每个对象。我目前能够显示所有项目,但需要能够只显示加载的第一个项目。单击按钮时,它需要迭代到数组中的下一个对象,并且只显示下一个对象,依此类推。
作为此功能的一个示例:http://jsbin.com/veyegihogi/edit?html,js,output
当前设置:
JavaScript:
var app = angular.module('app', []);
app.controller('portfolioController', function($scope, $http) {
$scope.indexToShow = 0;
$http.get("shows.json")
.then(function(response) {
console.log(response);
$scope.results = response.data;
});
$scope.change = function(){
$scope.indexToShow = ($scope.indexToShow + 1) % $scope.results.length;
};
});标记:
<div id="images" ng-repeat="items in results">
<div class="col-lg-2 col-md-2 col-sm-2">
<img src="{{items.image_url}}" alt="{{items.title}}">
</div>
</div>
<div class="simple-button" ng-click="change()">click me!</div>示例数据:
[
{
"id": 1,
"title": "title 1",
"count": 14,
"image_url": "images/image.jpg"
},
{
"id": 2,
"title": "title 2",
"count": 10,
"image_url": "images/image2.jpg"
},
{
"id": 3,
"title": "title 3",
"count": 8,
"image_url": "images/image3.jpg"
}
]发布于 2016-10-11 23:34:14
您已经为此准备好了所有代码;)
您只需要这个视图部分,而不是ng-repeat
<div id="images">
<img src="{{results[indexToShow].image_url}}" alt="{{results[indexToShow].title}}">
</div>
<div class="simple-button" ng-click="change()">click me!</div>发布于 2016-10-11 23:36:29
如果你想继续使用你的jsbin...
<div id="images" ng-repeat="item in results track by $index" ng-show="$index == indexToShow">
<div class="col-lg-2 col-md-2 col-sm-2">
<img src="{{item.image_url}}" alt="{{item.title}}">
</div>
</div>
<div class="simple-button" ng-click="change()">click me!</div>发布于 2016-10-11 23:53:23
我可以为selectedItem设置一个作用域变量并在控制器中进行索引
$scope.results = response.data;
$scope.selectedItem = $scope.results[0];
$scope.change = function(){
var currIdx = $scope.results.indexOf($scope.selectedItem),
nextIdx = currIdx+1 <= $scope.results.length-1 ? currIdx+1 : 0;
$scope.selectedItem=$scope.results[nextIdx ];
};视图
<img src="{{selectedItem.product_image_url}}"...>要创建页面导航按钮,在ng-click中设置选定项,或者将item传递给函数并在控制器中设置它:
<span ng-repeat="item in results"
ng-class="{active: item == selectedItem}}"
ng-click="selectedItem = item">{{$index+1}}</span>https://stackoverflow.com/questions/39981037
复制相似问题