How to obtain previous item in ng-repeat?

后端 未结 4 904
陌清茗
陌清茗 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:26

    You can do something like

    • {{$index}} - {{content.title}} - {{contents[$index - 1]}}

    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.

  • {{ correctContents[$index - 1] }} is the prev element
  • If you filter or orderBy, contents[$index] != content.

提交回复
热议问题