我想为我的n.name
执行ng-repeat,它显示每个项目,所以如果名称重复(就像在我的代码中 - 有三个“asd”),请在{{ 1}}每个重量。
这是我的代码
colspan="100%"
JS:
<p ng-repeat="n in messages">
{{n.name}}
{{n.weight}}
</p>
<table class="table">
<thead>
<tr>
<th>name</th>
<th>weight</th>
</tr>
</thead>
<tbody>
<tr ng-repeat-start="n in messages ">
<td>{{n.name}}</td>
<td> <button type="button" class="btn btn-default" ng-if="n.expanded" ng-click="expand(n);">-</button></button>
<button type="button" class="btn btn-default" ng-if="!n.expanded" ng-click="expand(n);">+</button>
</td>
</tr>
<tr ng-if="n.expanded" ng-repeat-end="">
<td colspan="100%" class="text">
{{n.weight}}
</td>
</tr>
</tbody>
</table>
答案 0 :(得分:1)
如何在渲染之前重新组合控制器中的数据
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.messages = [
{
'name' : 'asd',
'weight' : '19'
},
{
'name' : 'asd',
'weight' : '21'
},
{
'name' : 'asd',
'weight' : '26'
},
{
'name' : 'dsa',
'weight' : '17'
}
];
$scope.expand = function(select) {
var boolexpansion = !select.expanded;
angular.forEach($scope.messages, function(n) {
n.expanded = false;
});
select.expanded = !select.expanded;
}
$scope.regroup = function(){
var values = $scope.messages.reduce(function (obj, item) {
obj[item.name] = obj[item.name] || [];
obj[item.name].push(item.weight);
return obj;
}, {});
$scope.groupedMessages = Object.keys(values).map(function (key) {
return {name: key, weight: values[key]};
});
};
$scope.regroup();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<p ng-repeat="n in messages">
{{n.name}}
{{n.weight}}
</p>
<table class="table">
<thead>
<tr>
<th>name</th>
<th>weight</th>
</tr>
</thead>
<tbody>
<tr ng-repeat-start="n in groupedMessages ">
<td>{{n.name}}</td>
<td> <button type="button" class="btn btn-default" ng-if="n.expanded" ng-click="expand(n);">-</button></button>
<button type="button" class="btn btn-default" ng-if="!n.expanded" ng-click="expand(n);">+</button>
</td>
</tr>
<tr ng-if="n.expanded" ng-repeat-end="">
<td colspan="100%" class="text">
{{n.weight}}
</td>
</tr>
</tbody>
</table>
</div>
答案 1 :(得分:0)
也许更容易重新组织您的数据。
$scope.messages = [
{
name: 'asd',
weights: ['19', '20', '21']
},
{
name: 'dsa',
weights: ['17']
}
];
现在你可以对重量进行第二次重复重复。 重新组织数据的功能不应该如此难以编写。 类似的东西:
var foo = [
{
'name' : 'asd',
'weight' : '19'
},
{
'name' : 'asd',
'weight' : '21'
},
{
'name' : 'asd',
'weight' : '26'
},
{
'name' : 'dsa',
'weight' : '17'
}
];
var tempData = {};
foo.forEach(function(bar) {
if(!tempData[bar.name]) {
tempData[bar.name] = [bar.weight];
} else {
tempData[bar.name].push(bar.weight);
}
});
foo = [];
for(i in tempData) {
if (tempData.hasOwnProperty(i)) {
foo.push({name: i, weights: tempData[i]})
}
}
console.log(foo);
&#13;