最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Increment $index in ng-repeat - Stack Overflow

programmeradmin3浏览0评论

How should the $index in ng-repeat be incremented by a specific value? For instance in this fiddle / the value needs to be displayed two at a time. So the next iteration should start with third value instead of second value.

<div ng-controller="MyCtrl">
  <div ng-repeat="text in arr">
   <span>{{arr[$index]}}</span> 
   <span>{{arr[$index+1]}}</span> 
  </div>
</div>

How should the $index in ng-repeat be incremented by a specific value? For instance in this fiddle http://jsfiddle/Lvc0u55v/11811/ the value needs to be displayed two at a time. So the next iteration should start with third value instead of second value.

<div ng-controller="MyCtrl">
  <div ng-repeat="text in arr">
   <span>{{arr[$index]}}</span> 
   <span>{{arr[$index+1]}}</span> 
  </div>
</div>
Share Improve this question asked Nov 9, 2016 at 19:50 meteormeteor 2,5684 gold badges39 silver badges57 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

You can do this with a custom function in your controller that returns numbers from 0 to the length of your array, skipping every other value in between.

Modified jsfiddle

Here, I created a function called $scope.range().

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

function MyCtrl($scope) {
    $scope.arr=['hi1','hi2','hi3','hi4','hi5','hi6','hi7'];

    $scope.range = function(max, step) {
        step = step || 1;
        var input = [];
        for (var i = 0; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };
}

Use this new function in your ng-repeat by specifying the maximum number of elements to use and the number of elements to skip. So, to show every other element in arr, you would use num in range(arr.length, 2).

The function will create and return an array to the ng-repeat that looks like this:

[0, 2, 4, 6]

Your ng-repeat will be repeated four times (once for each item in this array) which corresponds to four rows. Then the two <span> elements will use the current value and the one after it to provide you with two columns.

<div ng-controller="MyCtrl">
  <div ng-repeat="num in range(arr.length, 2)">
    <span>{{arr[num]}}</span> 
    <span>{{arr[num+1]}}</span> 
  </div>
</div>

I've also modified your <span> elements to use arr[num] and arr[num+1] instead of using $index. This provides the results you're looking for.

You can, of course, modify this to use three columns by just changing the 2 to a 3 in the ng-repeat like this: <div ng-repeat="num in range(arr.length, 3)">

See the updated jsfiddle.

发布评论

评论列表(0)

  1. 暂无评论