如何使用angularjs正确格式化表中的JSON数据

How to properly format JSON data in table using angularjs?

本文关键字:JSON 数据 格式化 何使用 angularjs      更新时间:2024-06-09

我正在尝试创建一个表来显示从API接收的数据。数据采用JSON格式,需要使用AngularJS在表中显示。我可以在视图中检索所需的数据,但无法在表中正确格式化。代码在plunker中:https://plnkr.co/edit/GZtWlx5aDWvsseSs9ugW?p=preview

查看

<body ng-app="ShopOpeningHrs">
<div class="container" ng-controller="ScheduleCtrl">
    <table>
        <thead>
        <tr>
            <th>Sunday</th>
            <th>Monday</th>
            <th>Tuesday</th>
            <th>Wednesday</th>
            <th>Thursday</th>
            <th>Friday</th>
            <th>Saturday</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="schedule in singledayschedule">
            <td>{{ schedule.morning }}</td>
            <td>{{ schedule.evening }}</td>
        </tr>
        </tbody>
    </table>
</div>

角度

var app = angular.module("ShopOpeningHrs", []);
   app.controller("ScheduleCtrl", function($scope, $http) {
    $http.get('data.json').
    success(function(data, status, headers, config) {
        $scope.schedule = data[0];
        $scope.singledayschedule = [];
        angular.forEach($scope.schedule, function(value, key) {
            angular.forEach(value, function(value, key) {
                $scope.singledayschedule.push(value);
            });
        });
    console.log($scope.singledayschedule);
    }).
    error(function(data, status, headers, config) {
    // log error
    });
});

我认为您只需要使用两个ngRepeat循环:

  <tbody>
    <tr ng-repeat="(shop, schedule) in singledayschedule">
      <td>{{ shop }}</td>
      <td ng-repeat="(day, times) in schedule">
        <div>{{ times.morning }}</div>
        <div>{{ times.evening }}</div>
      </td>
    </tr>
  </tbody>

演示:https://plnkr.co/edit/CYSqQYFhENQfeeYRFTvp?p=preview