Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain previous item in ng-repeat?

People also ask

Where is the last element in NG-repeat?

You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .

How do I get an index value in ng-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

Does ng-repeat create a new scope?

Directives that Create Scopes In most cases, directives and scopes interact but do not create new instances of scope. However, some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element.

What does ng-repeat do?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.


You can do something like

<div ng-app="test-app" ng-controller="MyController">
    <ul id="contents">
      <li ng-repeat="content in contents">
          <div class="title">{{$index}} - {{content.title}} - {{contents[$index - 1]}}</div>
      </li>
    </ul>
</div>

JS

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

app.controller('MyController', function($scope){
    $scope.contents=[{
        title: 'First'
    }, {
        title: 'Second'
    }, {
        title: 'Third'
    }]
})

Demo: Fiddle


Be careful: $index is for the directive array, which may be different than the scope array. Use an inline variable to access the correct array.

<li ng-repeat="content in (correctContents = (contents | orderBy:'id'))">
  {{ correctContents[$index - 1] }} is the prev element
</li>

If you filter or orderBy, contents[$index] != content.


One way is to use the $index for targeting previous item:

HTML:

<div ng-repeat="item in items">
  <span>{{$index}}: </span>
  <span ng-show="items[$index-1].name=='Misko'" ng-bind="item.name"></span>
</div>

JS:

app.controller('AppController',
    [
      '$scope',
      function($scope) {
        $scope.items = [
          {name: 'Misko'},
          {name: 'Igor'},
          {name: 'Vojta'}
        ];

      }
    ]
  );

Plunker


Why not using key from ng-repeat ? ($index seems tricky compared to key)

<div ng-repeat="(key, item) in data">
  <p>My previous item is {{ data[key-1] }}, my actual item is {{ item }}
</div>