我在使用ng-repeat显示嵌套JSON时遇到问题。我有一个特定月份分配给某人的汽车清单。如果您搜索四月,您将获得四月数据。单击名称,它应填充Car部分。这是pluker。我有两个函数用于搜索按钮,另一个用于行单击。有人能告诉我推送嵌套汽车信息的正确方法吗?汽车信息在结果中。
$scope.results = [];
$scope.clickButton = function (enteredValue) {
$scope.items = $scope.info;
angular.forEach($scope.items[enteredValue], function (item, key) {
$scope.results.push({
name: item.Name,
address: item.Address,
phone: item.Phone,
status: item.Status,
cars:item.Cars
});
});
};
$scope.cars = [];
$scope.clickButton2 = function () {
$scope.rowItems = $scope.info.Cars;
angular.forEach($scope.rowItems, function(car, key){
$scope.cars.push({
vehicleMake: car.Make,
vehicleYear: car.Year
});
});
};
答案 0 :(得分:1)
实现此目标的最简单方法是利用$index
设置的ngRepeat
范围变量(请参阅the docs)。这允许您将结果项的索引传递给控制器方法,以便它知道从哪个结果读取汽车:
<tr ng-repeat="result in results">
<td ng-click='showCars($index)'>{{result.name}}</td>
<td>{{result.address}}</td>
<td>{{result.phone}}</td>
<td>{{result.status}}</td>
</tr>
然后您可以像这样使用索引:
$scope.showCars = function(resultIndex) {
$scope.cars = $scope.results[resultIndex].cars;
}
最后在页面上显示$scope.cars
:
<table>
<tr>
<th>Car</th>
<th>Year</th>
</tr>
<tr ng-repeat="car in cars">
<td>{{Make}}</td>
<td>{{Year}}</td>
</tr>
</table>
还有一件事:对于数组转换,例如示例代码中的属性lower-casing,请考虑使用Array map() method而不是angular.forEach()
。这是一个例子:
$scope.cars = $scope.results[resultIndex].cars.map(function(car) {
return {
make: car.Make,
year: car.Year
};
};