jgm*_*jgm 46 angularjs angularjs-ng-repeat
我有一个模板,我只想在当前项目与前一项目有不同的字段时生成一些HTML.如何访问ng-repeat中的上一项?
Aru*_*hny 99
你可以做点什么
<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>
Run Code Online (Sandbox Code Playgroud)
JS
var app = angular.module('test-app', []);
app.controller('MyController', function($scope){
$scope.contents=[{
title: 'First'
}, {
title: 'Second'
}, {
title: 'Third'
}]
})
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
注意: $index是指针数组,可能与作用域数组不同.使用内联变量来访问正确的数组.
<li ng-repeat="content in (correctContents = (contents | orderBy:'id'))">
{{ correctContents[$index - 1] }} is the prev element
</li>
Run Code Online (Sandbox Code Playgroud)
如果您过滤或订购,contents[$index] != content.
Ste*_*wie 12
一种方法是使用$ 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>
Run Code Online (Sandbox Code Playgroud)
JS:
app.controller('AppController',
[
'$scope',
function($scope) {
$scope.items = [
{name: 'Misko'},
{name: 'Igor'},
{name: 'Vojta'}
];
}
]
);
Run Code Online (Sandbox Code Playgroud)
为什么不使用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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34467 次 |
| 最近记录: |