Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

angularjs - How to obtain previous item in ng-repeat?

I have a template in which I want to generate some HTML only if the current item has some different fields from the previous item. How can I access the previous item in an ng-repeat?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...