如何获得ng-repeat中的上一项?

jgm*_*jgm 46 angularjs angularjs-ng-repeat

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

Aru*_*hny 99

你可以做点什么

<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>
Run Code Online (Sandbox Code Playgroud)

JS

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

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

演示:小提琴


注意: $index是指针数组,可能与作用域数组不同.使用内联变量来访问正确的数组.

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

如果您过滤或订购,contents[$index] != content.

  • @VadimAlekseev你可以做这样的事情来引用过滤后的数据:`ng-repeat ="item in(filteredData =(data | filter:term))"`并在@ arun-p-johny的回答中做` filteredData [$ index-1]`而不是`contents [$ index-1]` (22认同)
  • 但是,如果我在ng-repeat中进行过滤,那么这些集合将会产生差异.有任何想法吗? (3认同)

Ste*_*wie 12

一种方法是使用$ 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>
Run Code Online (Sandbox Code Playgroud)

JS:

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

      }
    ]
  );
Run Code Online (Sandbox Code Playgroud)

Plunker


mpg*_*pgn 6

为什么不使用keyng-repeat?($index相比之下似乎很棘手key)

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