我使用ng-repeat循环遍历我想要打印编号标题的对象数组。
例如:
控制器
var cars = [
{make:'ford',model:'mustang'},
{make:'ford',model:'fusion'},
{make:'bwm',model:'x5'},
{make:'honda',model:'civic'},
{make:'honda',model:'accord'},
{make:'toyota',model:'camry'},
{make:'honda',model:'crv'},
];
查看
<div ng-repeat="car in cars" ng-show="car.make=='ford'">
<h1>Fords:</h1>
<div><b>{{$index}})</b> {{car.model}}</div>
</div>
<div ng-repeat="car in cars" ng-show="car.make=='honda'">
<h1>Hondas:</h1>
<div><b>{{$index}})</b> {{car.model}}</div>
</div>
预期输出
Fords:
0) mustang
1) fusion
Hondas:
0) civic
1) accord
2) crv
实际输出
Fords:
0) mustang
1) fusion
Hondas:
3) civic
4) accord
6) crv
换句话说,在每个循环中,$ index维护对源数组的引用。我认为这是有意义的,但我认为$ index的目的是计算给定循环范围内的迭代?
如何使用$ index(或其他内容)来实现预期输出?
答案 0 :(得分:1)
一个简单的解决方案是创建一个仅返回匹配元素的过滤数组。然后您可以正确使用$index
来打印订购号。
<body ng-app="textInputExample">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var cars = [{
make: 'ford',
model: 'mustang'
}, {
make: 'ford',
model: 'fusion'
}, {
make: 'bwm',
model: 'x5'
}, {
make: 'honda',
model: 'civic'
}, {
make: 'honda',
model: 'accord'
}, {
make: 'toyota',
model: 'camry'
}, {
make: 'honda',
model: 'crv'
}, ];
$scope.cars = cars;
$scope.filteredcars = function(make){
return $scope.cars.filter(function(e) { return e.make === make });
};
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="car in filteredcars('honda')">
<h1>Hondas:</h1>
<div><b>{{$index}})</b> {{car.model}}</div>
</div>
</div>
</body>
答案 1 :(得分:0)
你可以通过orderBy
道具make
来做类似下面的事情。它不是刚性解决方案。此外,您可以使用自定义filter
按make
属性创建新的分组对象集合。
加价
<div ng-repeat="car in cars | orderBy: 'make'">
<h1 ng-if="cars[$index].make != cars[$index-1].make">
{{car.make}}:
</h1>
<div><b>{{$index + 1}})</b> {{car.model}}</div>
</div>
答案 2 :(得分:0)
Demo link此处。
<div ng-app ng-controller="Main">
<div ng-repeat="carPerMake in carsToFilter() | filter:filterMake">
<b>{{carPerMake.make}}:</b>
<div ng-repeat="car in cars | filter:{make: carPerMake.make}"> {{$index}} - {{car.model}}</div>
<br>
</div>
</div>
function Main($scope) {
$scope.cars = [{
make: 'ford',
model: 'mustang'
}, {
make: 'ford',
model: 'fusion'
}, {
make: 'bwm',
model: 'x5'
}, {
make: 'honda',
model: 'civic'
}, {
make: 'honda',
model: 'accord'
}, {
make: 'toyota',
model: 'camry'
}, {
make: 'honda',
model: 'crv'
}, ];
var makeArr = [];
$scope.carsToFilter = function() {
makeArr = [];
return $scope.cars;
}
$scope.filterMake = function(car) {
var newMake = makeArr.indexOf(car.make) == -1;
if (newMake) {
makeArr.push(car.make);
}
return newMake;
}
}
福特: 0 - 野马 1 - 融合
BWM: 0 - x5
本田: 0 - 思域 1 - 一致 2 - crv
丰田: 0 - 凯美瑞