sourcecode

ng-repeat에서 이전 항목을 얻는 방법은 무엇입니까?

codebag 2023. 3. 9. 22:02
반응형

ng-repeat에서 이전 항목을 얻는 방법은 무엇입니까?

현재 아이템의 필드가 이전 아이템과 다른 경우에만 HTML을 생성하려는 템플릿이 있습니다.ng-repeat에서 이전 항목에 접속하려면 어떻게 해야 하나요?

뭐 이런 거 할 수 있어요

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

데모: 바이올린


주의: $index는 지시 배열용이며 스코프 배열과는 다를 수 있습니다.인라인 변수를 사용하여 올바른 배열에 액세스합니다.

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

필터링 또는 주문 기준의 경우contents[$index] != content.

한 가지 방법은 이전 항목을 대상으로 $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'}
        ];

      }
    ]
  );

플런커

를 사용하지 않는 이유key부터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>
<li ng-repeat="item in items">
    {{items[$index - 1].att == item.att ? 'current same as previous' : 'current not same as previous'}}
</li>

언급URL : https://stackoverflow.com/questions/15412897/how-to-obtain-previous-item-in-ng-repeat

반응형