下面是我的 plunker,我尝试在每个类别下显示数据。但是数据没有按预期打印。示例:-rom 值 12345 应该直接位于面包下。 我不确定我的代码哪里做错了:
$scope.allProducts = [];
angular.forEach($scope.data,function(item, index){
angular.forEach(item.products, function(item2, index){
if($scope.allProducts.indexOf(item2.consummable) == -1){
$scope.allProducts.push(item2.consummable);
}
})
})
最佳答案
又一个变体,改变了 ng-repeat
表达式。由于您在第一行重复allProducts,因此您需要在其他行中重复它,并过滤所选值的数据。请参阅下面的代码片段
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.data =[
{
"resource": "100",
products: [
{
"consummable": "milk",
"rom": 1
},
]
},
{
"resource": "200",
products: [
{
"consummable": "bread",
"rom": 12345
},
]
},
{
"resource": "300",
products: [
{
"consummable": "butter",
"rom": 123456789
}
]
}
];
$scope.allProducts = [];
angular.forEach($scope.data,function(item, index){
angular.forEach(item.products, function(item2, index){
if($scope.allProducts.indexOf(item2.consummable) == -1){
$scope.allProducts.push(item2.consummable);
}
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<table style="border:1px solid red;">
<tr>
<td>
</td>
<td ng-repeat="itemProd in allProducts" style="border:1px solid red;">
{{itemProd}}
</td>
</tr>
<tr ng-repeat="item in data">
<td>
{{item.resource}}
</td>
<td ng-repeat="item2 in allProducts" style="border:1px solid red;" ng-init="product=(item.products | filter: {consummable:item2})[0]">
<a>{{product.rom}}</a>
</td>
</tr>
</table>
{{allProducts}}
{{data}}
</div>
关于javascript - 无法在表中显示正确的数据 -AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32517107/