在angularjs中实现包含行和列标题的表

时间:2017-03-09 08:50:51

标签: angularjs html-table row

我有一个包含行标题和列标题的表格。目前行标题的值也存在于json中,我将检索该值以显示在表中。所以我直接在角度表达式中映射了行标题。问题是,如果从json检索数据时出现一些错误,则根本不会显示行标题。我希望在没有响应的情况下显示带有行和列标题的空表。请告诉我如何实施。如果我从json中取出行标题并直接用行和列标题创建一个表,我将如何显示从json接收的数据? 这是我的代码:

HTML

<body ng-controller="jsonCtrl">    
<table class="table table-striped table-bordered">
<caption>Delivery slots:</caption>
<tr>
<td></td>
<th scope="col">Monday</th>
<th scope="col">Tuesday</th>
<th scope="col">Wednesday</th>
<th scope="col">Thursday</th>
<th scope="col">Friday</th>
</tr>
<tr ng-repeat="data in timetable">
<th scope="row">{{data.time}}</th>
<td>{{data.Monday}}</td>
<td>{{data.Tuesday}}</td>
<td>{{data.Wednesday}}</td>
<td>{{data.Thursday}}</td>
<td>{{data.Friday}}</td>
</tr>
</table>
</body>

JS

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

myApp.controller('jsonCtrl', function($scope, $http){
$http.get('timetable.json').success(function (data){
    $scope.timetable = data;
});
});

JSON

[
  {
    "Monday": "Physics",
    "Tuesday": "Chemistry",
    "Wednesday": "Maths",
    "Thursday": "English",
    "Friday": "Computers",
    "time": "09:00 - 11:00"
  },
  {
    "Monday": "Maths",
    "Tuesday": "Games",
    "Wednesday": "Physics",
    "Thursday": "Computers",
    "Friday": "Chemistry",
    "time": "11:00 - 13:00"
  },
  {
    "Monday": "Computers",
    "Tuesday": "Physics",
    "Wednesday": "Maths",
    "Thursday": "German",
    "Friday": "History",
    "time": "13:00 - 15:00"
  },
  {
    "Monday": "Accounts",
    "Tuesday": "Maths",
    "Wednesday": "Physics",
    "Thursday": "French",
    "Friday": "Chemistry",
    "time": "15:00 - 17:00"
  }

]

以下是更好解释的plunker链接。 json中存在的'time'需要是行标题。 https://plnkr.co/edit/SZP9tdRX7pD9oaT9uOR1?p=preview

1 个答案:

答案 0 :(得分:1)

如果http调用失败,您可以使用如下数组:

[
  {
    "time": "09:00 - 11:00"
  },
  {
    "time": "11:00 - 13:00"
  },
  {
    "time": "13:00 - 15:00"
  },
  {
    "time": "15:00 - 17:00"
  }

]

所以必须改变控制器:

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

myApp.controller('jsonCtrl', function($scope, $http){
$http.get('timetable.json').then(function (data){
    $scope.timetable = data;
},
//error callback
function (response){
$scope.timetable = [
  {
    "time": "09:00 - 11:00"
  },
  {
    "time": "11:00 - 13:00"
  },
  {
    "time": "13:00 - 15:00"
  },
  {
    "time": "15:00 - 17:00"
  }

]
}
);
});