How to obtain previous item in ng-repeat?

后端 未结 4 905
陌清茗
陌清茗 2020-12-03 00:51

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

相关标签:
4条回答
  • 2020-12-03 01:14
    <li ng-repeat="item in items">
        {{items[$index - 1].att == item.att ? 'current same as previous' : 'current not same as previous'}}
    </li>
    
    0 讨论(0)
  • 2020-12-03 01:15

    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>
    
    0 讨论(0)
  • 2020-12-03 01:26

    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.

    0 讨论(0)
  • 2020-12-03 01:27

    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

    0 讨论(0)
提交回复
热议问题