現在のアイテムに前のアイテムとは異なるフィールドがある場合にのみHTMLを生成したいテンプレートがあります。ng-repeatで前のアイテムにアクセスするにはどうすればよいですか?
36553 次
4 に答える
102
あなたは次のようなことをすることができます
<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>
フィルタリングまたはorderByの場合、contents[$index] != content
。
于 2013-03-14T15:20:09.083 に答える
11
1つの方法は、前のアイテムをターゲットにするために$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
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>
于 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 に答える