我想为我的 n.name
做 ng-repeat,它显示每个项目,所以如果名称重复(就像在我的代码中 - 有三个“asd”)让显示对于 colspan="100%"
每个权重。
这是我的代码
<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>
JS:
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;
});
if(boolexpansion) {
select.expanded = !select.expanded;
}
}
});
最佳答案
在渲染之前在 Controller 中重新组合数据怎么样
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>
关于javascript - ng-repeat 显示项目的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894059/