If you want to display every other element from an array in your Angular controller, you can achieve this using a custom function that generates a new array with the desired elements.
Check out the modified jsfiddle
In the example provided, a function named $scope.range()
has been created for this purpose.
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;
};
}
You can then use this new function in your ng-repeat
directive by indicating the maximum number of elements to include and the increment value to skip elements. For instance, to display every other element from arr
, you would use num in range(arr.length, 2)
.
The function will generate an array like the following to be used by the ng-repeat
:
[0, 2, 4, 6]
Your ng-repeat
will iterate four times based on this new array, resulting in four rows. Each pair of <span>
elements within it will correspond to two columns displaying consecutive values.
<div ng-controller="MyCtrl">
<div ng-repeat="num in range(arr.length, 2)">
<span>{{arr[num]}}</span>
<span>{{arr[num+1]}}</span>
</div>
</div>
To achieve three columns instead, you can simply adjust the increment value in the ng-repeat
statement to 3 like so:
<div ng-repeat="num in range(arr.length, 3)">
For more details and to view the updated code, please refer to the revised jsfiddle.