【发布时间】:2013-03-03 00:23:03
【问题描述】:
我有一个模板,只有当当前项目与前一个项目有一些不同的字段时,我才想在其中生成一些 HTML。如何访问 ng-repeat 中的上一个项目?
【问题讨论】:
标签: angularjs angularjs-ng-repeat
我有一个模板,只有当当前项目与前一个项目有一些不同的字段时,我才想在其中生成一些 HTML。如何访问 ng-repeat 中的上一个项目?
【问题讨论】:
标签: angularjs angularjs-ng-repeat
<li ng-repeat="item in items">
{{items[$index - 1].att == item.att ? 'current same as previous' : 'current not same as previous'}}
</li>
【讨论】:
为什么不使用来自ng-repeat 的key ? ($index 与 key 相比似乎有些棘手)
<div ng-repeat="(key, item) in data">
<p>My previous item is {{ data[key-1] }}, my actual item is {{ item }}
</div>
【讨论】:
你可以这样做
<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'
}]
})
演示:Fiddle
小心: $index 用于指令数组,可能与作用域数组不同。使用内联变量访问正确的数组。
<li ng-repeat="content in (correctContents = (contents | orderBy:'id'))">
{{ correctContents[$index - 1] }} is the prev element
</li>
如果您过滤或排序,contents[$index] != content。
【讨论】:
ng-repeat="item in (filteredData = (data | filter:term))" 并在@arun-p-johny 的答案中使用filteredData[$index-1] 而不是contents[$index-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'}
];
}
]
);
【讨论】: