46

我有一个模板,只有当当前项目与前一个项目有一些不同的字段时,我才想在其中生成一些 HTML。如何访问 ng-repeat 中的上一个项目?

4

4 回答 4

102

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.

于 2013-03-14T15:20:09.083 回答
11

一种方法是使用 $index 来定位上一个项目:

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'}
        ];

      }
    ]
  );

普朗克

于 2013-03-14T15:19:01.877 回答
6

为什么不使用keyfrom ng-repeat?($index与之相比似乎很棘手key

<div ng-repeat="(key, item) in data">
  <p>My previous item is {{ data[key-1] }}, my actual item is {{ item }}
</div>
于 2015-10-12T13:45:27.337 回答
0
<li ng-repeat="item in items">
    {{items[$index - 1].att == item.att ? 'current same as previous' : 'current not same as previous'}}
</li>
于 2018-06-21T13:11:06.290 回答