如何在 ng-repeat 中获取上一项? [英] How to obtain previous item in ng-repeat?
本文介绍了如何在 ng-repeat 中获取上一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模板,仅当当前项目与前一个项目有一些不同的字段时,我才想在其中生成一些 HTML.如何在 ng-repeat 中访问上一项?
解决方案
你可以这样做
<ul id="内容"><li ng-repeat="内容中的内容"><div class="title">{{$index}} - {{content.title}} - {{contents[$index - 1]}}</div>
JS
var app = angular.module('test-app', []);app.controller('MyController', function($scope){$scope.contents=[{标题:'第一'}, {书名:《第二》}, {书名:《第三》}]})
演示:小提琴
<小时>注意: $index
用于指令数组,它可能与作用域数组不同.使用内联变量访问正确的数组.
{{correctContents[$index - 1] }} 是 prev 元素
如果您过滤或排序,contents[$index] != content
.
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 ng-repeat?
解决方案
You can do something like
<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'
}]
})
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.
<li ng-repeat="content in (correctContents = (contents | orderBy:'id'))">
{{ correctContents[$index - 1] }} is the prev element
</li>
If you filter or orderBy, contents[$index] != content
.
这篇关于如何在 ng-repeat 中获取上一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文