【问题标题】:How to make `slice` the array element by required length and update如何按所需长度对数组元素进行“切片”并更新
【发布时间】:2015-06-23 17:04:23
【问题描述】:

我有一个数组项目,我想通过3 显示项目3。为此,我正在切割物品。

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

我有nextprev 链接可供点击。 next 提供1 添加,previous 提供-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)你想删除哪个元素???请清楚...
  • 我不想删除任何东西。我正在做幻灯片过程。所以一切都需要。

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


【解决方案1】:

您的代码如下所示

标记

<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

【讨论】:

  • 不,我想通过下一组数组更新,例如。 1,2,3第一组,第二组是4,5,6,第三组应该是7,8,9,最后一个0。并且任何一个元素单击示例:179 标题应使用该元素更新。如果点击 7,标题应该是 7。
  • Array.prototype.slice 复制源数组的一部分,因此您的angular.copy 调用不是必需的。
  • @user2024080 你想要这样的plnkr.co/edit/UHUryYHZYo9eAXF4Wdvo?p=preview 吗?
  • 首先我收到1,2,3,但4 不存在。并且不点击 h2 元素我不想更新标题。
  • @user2024080 请先更新您的问题..您在我回答时添加内容..首先清除要求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-03
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多