如何通过所需的长度和更新来“切片”数组元素

时间:2015-06-23 17:04:24

标签: javascript jquery arrays angularjs angularjs-ng-repeat

我有一个数组项目,我希望33显示项目。因为我正在切片。

当附加切片项目时,在点击切片项目时,我想将该项目更新为heading项目。

我点击了nextprev链接。下一步提供1添加,之前提供-1减少长度。

我以某种方式尝试过,但我无法找到正确的方法。有没有人帮我完成这件事?

我的代码:

<div ng-controller="main" class="content">
      <h1>{{heading}}</h1>
      <a ng-click="slide(-1)">Prev</a>
        <h2 ng-repeat="title in titles">{{title}}</h2>
      <a ng-click="slide(1)">Prev</a>
    </div>

var myApp = angular.module('myApp', []);

myApp.controller("main", function($scope) {
  $scope.required = 3;
  $scope.items = [1,2,3,4,5,6,7,8,9,0];
  $scope.titles = $scope.items.slice(0,3);
  $scope.heading = $scope.titles[0];

  $scope.slide = function (num) {
    console.log(num);
  }

})

Live Demo

1 个答案:

答案 0 :(得分:2)

您的代码如下所示

<强>标记

<div ng-controller="main" class="content">
  <h1>{{heading}}</h1>
  <a ng-click="prev(-1)">Prev</a>
    <h2 ng-repeat="title in titles">{{title}}</h2>
  <a ng-click="next(1)">Next</a>
</div>

<强>控制器

myApp.controller("main", function($scope) {
  $scope.required = 3;
  $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  $scope.titles = angular.copy($scope.items).slice(0, 3);
  $scope.heading = $scope.titles[0];

  $scope.startIndex = 0;
  $scope.next = function(num) {
    if ($scope.startIndex < $scope.items.length) {
      $scope.startIndex = $scope.startIndex + 2;
      $scope.titles = Array.prototype.slice.call($scope.items, ++$scope.startIndex, $scope.startIndex + 3);
    }
  }

  $scope.prev = function(num) {
    if ($scope.startIndex > 0) {
      $scope.startIndex = $scope.startIndex - 2;
      $scope.titles = Array.prototype.slice.call($scope.items, --$scope.startIndex, $scope.startIndex + 3);

    }
  }

  $scope.updateHeading = function(item) {
    $scope.heading = item;
  }

})

Demo Plunkr