当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Angular repeat structure based on value

问题描述:

I have a following json structure that I would like to turn into table.

What would be the best approach here? Groups 1 and -1 would represent Positive and Negative respectivly. These can or cannot be presented in data, but must be defined in table.

Expected result

 | Very Positive | Positive | Neutral | Negative | Very Negative |

-----------+---------------+----------+---------+----------+---------------|

Cleaniness | 16 | 0 | 11 | 0 | 30 |

Staff | 20 | 0 | 15 | 0 | 37 |

-----------+---------------+----------+---------+----------+---------------|

Data:

{

"Cleanliness": [

{

"group": "-2",

"count": 30

},

{

"group": "0",

"count": 11

},

{

"group": "2",

"count": 16

}

],

"Staff": [

{

"group": "-2",

"count": 37

},

{

"group": "0",

"count": 15

},

{

"group": "2",

"count": 20

}

]

}

Any help appreciated, thanks in advance!

网友答案:

You can do using ngRepeat on a fixed array of values ng-repeat="pos in [2, 1, 0, -1, -2]":

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

app.controller('demoCtrl', function() {

  var stats = {
    "Cleanliness": [{
      "group": "-2",
      "count": 30
    }, {
      "group": "0",
      "count": 11
    }, {
      "group": "2",
      "count": 16
    }],
    "Staff": [{
      "group": "-2",
      "count": 37
    }, {
      "group": "0",
      "count": 15
    }, {
      "group": "2",
      "count": 20
    }]
  };

  /** we want to transform original data to this structure 
  [{
    name: "Cleanliness",
    data: {
      '-2': 30,
      '0': 11,
      '2': 16
    }
  }, {
    name: "Staff",
    data: {
      '-2': 37,
      '0': 15,
      '2': 20
    }
  }]
  **/

  this.stats = Object.keys(stats).map(function(category) {
    return {
      name: category,
      data: stats[category].reduce(function(obj, stat) {
        obj[stat.group] = stat.count;
        return obj;
      }, {})
    };

  });

});
table {
  border-collapse: collapse;
}
th,
td {
  padding: 0 3px;
  border: 1px solid blue;
}

td:not(:first-child) {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="demo" ng-controller="demoCtrl as demo">

  <table>

    <thead>
      <tr>
        <th></th>
        <th>Very Positive</th>
        <th>Positive</th>
        <th>Neutral</th>
        <th>Negative</th>
        <th>Very Negative</th>
      </tr>
    </thead>

    <tbody>
      <tr ng-repeat="category in demo.stats">
        <td>{{category.name}}</td>
        <td ng-repeat="pos in [2, 1, 0, -1, -2]">
          {{category.data[pos] || 0}}
        </td>
      </tr>
    </tbody>

  </table>

</div>
分享给朋友:
您可能感兴趣的文章:
随机阅读: