简体   繁体   中英

Displaying data with ng-repeat from JSON array in angular

Hi I have following data that is returned from service which I do not have any control on how it is returned:

{"day_1":[{"classroom":"Nursery","count":0},{"classroom":"Junior Kindy","count":1}],"day_2":[{"classroom":"Nursery","count":4},{"classroom":"Junior Kindy","count":0}]}

but I need to display it in pivot format that is like below:

classroom    | day_1  | day_2
============  ======== ======
Nursery      | 0      | 4
Junior Kindy | 1      | 0

This is the code in controller

$scope.rolls=[];

Rolls.getRollMarked().then(
    function(data){
        console.log(data.data);
        $scope.rolls = data.data;
    }
)

in the view I am using following but it doesn't display any count for the day and I am not sure how to display it..so please let me know how can I display it in the above format?

   <table class="table table-bordered">
      <tr>
         <td>Classroom</td>
         <td>day_1</td>
         <td>day_2</td>
       </tr>
       <tr ng-repeat="roll in rolls">
          <td> 
            {{roll[$index]['classroom']}}
          </td>
          <td>
              {{roll.day_1}}
               </td>
               <td>
                   {{roll.day_2}}
               </td>
            </tr>
     </table>

You need to convert your data. ng-repeat as you have set it up expects an array.

Using some easy code you can get it to an array though, and then your code will work alright.

Also, you should update your html. You don't need to reference items using $index since each item is bound to the iterator variable in that case

<table class="table table-bordered">
  <tr>
     <th>Classroom</th>
     <th>day_1</th>
     <th>day_2</th>
   </tr>
   <tr ng-repeat="roll in rolls">
      <td> 
        {{roll.classroom}}
      </td>
      <td>
        {{roll.day_1}}
      </td>
      <td>
        {{roll.day_2}}
      </td>
   </tr>
</table>

And then call a convert function that makes the data into an array. I've used lodash.find here, so you either need to reference that or use your own find method.

Rolls.getRollMarked().then(
    function(data){
        console.log(data.data);
        $scope.rolls = convert(data.data);
    }
)

function convert(json) {
    var rolls = [];
    var days = ['day_1', 'day_2'];
    for (var d = 0; d < days.length; ++d) {
      var day = days[d];
      for (var i = 0; i < json[day].length; ++i) {
        var classroom = json[day][i];
        var existing = _.find(rolls, { "classroom": classroom.classroom });
        if (!existing) {
          existing = { classroom: classroom.classroom };
          rolls.push(existing);
        }
        existing[day] = classroom.count;
      }
    }
    return rolls;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM