Javascript 如何使'slice'按所需长度作为数组元素并进行更新
我有一个数组项,我想按Javascript 如何使'slice'按所需长度作为数组元素并进行更新,javascript,jquery,arrays,angularjs,angularjs-ng-repeat,Javascript,Jquery,Arrays,Angularjs,Angularjs Ng Repeat,我有一个数组项,我想按3按3显示项。为此,我正在切片的项目 当添加切片项目时,单击切片项目,我想将该项目更新为标题项目 我有next和prev链接可以点击。下一步提供要添加的1,上一步提供-1减少长度 我尝试了一些方法,但没有找到正确的方法。有人帮我把这件事做完吗 我的代码: <div ng-controller="main" class="content"> <h1>{{heading}}</h1> <a ng-click="s
3
按3
显示项。为此,我正在切片的项目
当添加切片项目时,单击切片项目,我想将该项目更新为标题
项目
我有next
和prev
链接可以点击。下一步提供要添加的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);
}
})
{{heading}}
您的代码如下所示
标记
<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>
{{heading}}
单击上一页(即-1),您要删除哪个元素???请澄清…我不想移除任何东西。我正在做幻灯片过程。所以所有的都需要。不,我想用下一组数组来更新,例如1,2,3第一组和第二组是4,5,6,第三组应该是7,8,9,
最后一组0
。然后单击任何一个元素,例如:1
或7
或9
标题应使用该元素更新。如果单击7,则标题应为7。Array.prototype.slice
复制源数组的一部分,因此不需要调用angular.copy
。@user2024080您想要这样的标题吗?首先,我得到1,2,3
,但4
不存在。如果不单击h2
元素,我不想更新标题。@user2024080请先更新您的问题。.您正在添加我回答的内容。。首先明确要求
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;
}
})