angularjs ngrepet相同的数据合并

时间:2017-03-17 08:23:16

标签: angularjs angularjs-ng-repeat

ng-repeat我有相同的但不同的金额&的类别即可。

我的问题是,如果同月不应该循环该月<td></td>

<table>
    <tbody>
     <tr ng-repeat="data in myCtrl.value">
        <td class="text-center">{{data.month}}</td>
        <td class="text-center">{{data.amountval}}</td>
        <td class="text-center">{{data.categoryval}}</td>
     </tr>
  </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您可以使用月份对数据进行分组,并在表格中应用行数。

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.finalLoopData = {};
  $scope.loopData = [{month:'Jan',amountval:'30',categoryval:'50'},
  {month:'Jan',amountval:'30',categoryval:'50'},
  {month:'Jan',amountval:'30',categoryval:'50'},
  {month:'Jan',amountval:'30',categoryval:'50'},
  {month:'Feb',amountval:'30',categoryval:'50'},
  {month:'Feb',amountval:'30',categoryval:'50'},
  {month:'Feb',amountval:'30',categoryval:'50'},
  {month:'Feb',amountval:'30',categoryval:'50'}
  ];
  
  $scope.arrayToObject = function () {
            var finalLoopData = {};
            angular.forEach($scope.loopData, function (value, key) {
                if (!finalLoopData[value.month]) { 
                    finalLoopData[value.month] = new Array();
                }
                finalLoopData[value.month].push(value);
            });
            $scope.finalLoopData = finalLoopData;
        }
        $scope.arrayToObject();
});
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <table>
    <tbody ng-repeat="monthGroup in finalLoopData">
     <tr ng-repeat="loopData in monthGroup">
        <td class="text-center" rowspan="{{monthGroup.length}}" ng-if="$index===0">{{loopData.month}}</td>
        <td class="text-center">{{loopData.amountval}}</td>
        <td class="text-center">{{loopData.categoryval}}</td>
     </tr>
  </tbody>
</table>
  </body>

</html>