How to display list items using index in AngularJS ng-repeat

10,024

DEMO - http://jsfiddle.net/softvar/yk8phbc5/

JS:

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

app.controller('myCtrl', function ($scope) {
    $scope.results = [
        {birthDate: '01/08/1982'},
        {birthDate: '11/08/1992'},
        {birthDate: '21/08/2002'},
        {birthDate: '31/08/2012'}
    ]
});

HTML:

<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-repeat="result in results" ng-if="$index % 2 == 0" class="row">
        <div class="col-xs-6">First: {{results[$index].birthDate}}</div>
        <div class="col-xs-6">Second: {{results[$index + 1].birthDate}}</div>
        <br/>
    </div>
</div>
Share:
10,024
Maverick Riz
Author by

Maverick Riz

Updated on June 04, 2022

Comments

  • Maverick Riz
    Maverick Riz almost 2 years

    I have a requirement to display the list of items in angular with each row having only 2 items. Suppose there are 5 items in the list, the output should be 3 rows with first 2 rows with 2 columns and last row with one column.

    <div ng-repeat="result in results" ng-if="$index % 2 == 0" class="row">
        <div class="col-xs-6">{{result[$index]}}</div>
        <div class="col-xs-6">{{result[$index + 1]}}</div>
    </div>

    Above is the code, this code works fine when the result is a list of items. But when the result is a list of objects it does not print. Example, if result object has birthDate or Id property how do i display those? {{result.birthDate}} prints the correct value but how do I print the index + 1 value ? I tried {{result[$index + 1].birthDate}} or {{result.birthDate[$index + 1]}} does not work. The below code does not work but, i need something like this,

    <div ng-repeat="result in results" ng-if="$index % 2 == 0" class="row">
        <div class="col-xs-6">{{result[$index].birthDate}}</div>
        <div class="col-xs-6">{{result[$index + 1].birthDate}}</div>
    </div>

    Appreciate your help

    • shreyansh
      shreyansh almost 9 years
      Are you sure that {{result[$index]}} and {{result[$index + 1]}} were working because for me they are not giving any output, but when I tried results instead of result its working fine.
    • Maverick Riz
      Maverick Riz almost 9 years
      that was my bad. Yes, it need to be results as pointed by @softvar and wZVang
  • Maverick Riz
    Maverick Riz almost 9 years
    Thanks, this works fine but now the problem is, if i have odd no. of results i get the empty place holder "Second". Example, if i have 3 items in result, i get 2 rows, which is correct but for second row i get two columns when i should get only one column. The second column has only empty place holder. How to avoid this? Please take a look at this jsfiddle jsfiddle.net/yk8phbc5/1
  • Maverick Riz
    Maverick Riz almost 9 years
    Yes @wZVanG, even for your answer i get the empty place holder. jsfiddle.net/yk8phbc5/1. How to avoid this? Thanks