使用Angular逐步执行JSON对象

时间:2016-10-11 15:30:07

标签: javascript angularjs json

我有一个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"
  }
]

3 个答案:

答案 0 :(得分:0)

您准备好了所有代码;)

您只需要此视图部分而不是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>

答案 1 :(得分:0)

如果你想坚持你的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>

答案 2 :(得分:0)

可以为final Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_icon).mutate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.image.setBackground(drawable); } else { holder.image.setBackgroundDrawable(drawable); } 设置范围变量,并在控制器中进行索引

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