[英]numer specific items in ng-repeat (Angular)
Assume the following object 假设以下对象
var items [
{ type: 'big', .... },
{ type: 'small', .... },
{ type: 'big', .... },
{ type: 'small', .... },
{ type: 'big', .... },
];
Which I use inside a ng-repeat
as follows: 我在ng-repeat
中使用如下:
<div ng-repeat="item in items">
<span ng-if="item.type === 'big'>{{$index}}</div>
<p> ..... </p>
</div>
The problem with this code is that I only want to number the items with type === 'big'
and I don't wan't gapes in the numbering. 这段代码的问题在于,我只想对type === 'big'
的项目进行编号,而我不会在编号上留有空白。 The output now is: 现在的输出是:
<div>
<span>0</div>
<p>......</p>
</div>
<div>
<p>......</p>
</div>
<div>
<span>2</div> // I want a 1 here
<p>......</p>
</div>
<div>
<p>......</p>
</div>
<div>
<span>4</div> // and a 2 here!
<p>......</p>
</div>
What would be the angular way to perform this kind of numbering ? 进行这种编号的角度方式是什么?
You could call a scoped function in your ng-if
statement that will check if the item.type === "big"
and also keeps track of the number of times item.type !== "big"
and subtract that number from the index of the repeated element. 您可以在ng-if
语句中调用作用域函数,该函数将检查item.type === "big"
的数量,并还会跟踪item.type !== "big"
次数,并从重复元素的索引。
Inside your Angular controller: 在您的Angular控制器中:
$scope.skipped = 0;
$scope.isBig = function(type) {
if (type === "big") {
return true;
else {
$scope.skipped++;
return false;
}
}
HTML: HTML:
<div ng-repeat="item in items">
<span ng-if="isBig(item.type)">{{$index - skipped}}</div>
<p> ..... </p>
</div>
The solution I am proposing isn't an Angular solution at all. 我提出的解决方案根本不是Angular解决方案。 But instead I am going to use CSS to solve your solely displaying issue: 但是相反,我将使用CSS来解决您的唯一显示问题:
CSS counters are implemented in all major browsers and therefore a usable possibility ( canIUse.com ) CSS计数器已在所有主要浏览器中实现,因此是可行的方法( canIUse.com )
You reset an css counter for the sorrounding element and increment it for every shown element: 您为sorrounding元素重置一个css计数器,并为每个显示的元素递增它:
<div class="list">
<div ng-repeat="item in items">
<p ng-class="item.type"> ..... </p>
</div>
</div>
and trhe corresponding CSS: 和相应的CSS:
.list{
counter-reset: big-counter;
}
.list .big:before {
content: counter(big-counter);
counter-increment: big-counter;
}
I made this Plunker to show the result. 我制作了这个Plunker来显示结果。
To use characters instead of numbers you change the css counter line to the following: 要使用字符而不是数字,请将css计数器行更改为以下内容:
content: counter(big-counter,lower-latin);
or 要么
content: counter(big-counter, upper-latin);
Updated Plunker (by Jeanluca Scaljeri) 更新的“ Plunker” (作者Jeanluca Scaljeri)
This isn't angular, it's math 这不是角度,是数学
<span ng-if="item.type === 'big'>{{$index/2}}</div>
Just divide the index by 2! 只需将索引除以2!
Sure, you could do some funny stuff in the controller, but this is probably the fastest and easiest. 当然,您可以在控制器中做一些有趣的事情,但这可能是最快,最简单的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.