我刚刚开始为我的项目使用Angular。手头的任务是,我需要从JSON生成一个表。我能够通过对所有内容进行硬编码来实现这一点,但项目的改变方式使我现在需要使用JSON。我想用ng-repeat。我的数据结构是一个对象数组,其中包含表示业务和小时的嵌套对象。我得到了奇怪的行为,我想知道是否是我的数据结构导致它。
我创造了一个小提琴。任何建议都将不胜感激。
我的数据结构如下:
var dept = {
sales : { startTime : "", endTime : "" },
service : { startTime : "", endTime : "" },
accounting : { startTime : "", endTime : "" },
parts : { startTime : "", endTime : "" },
bodyShop : { startTime : "", endTime : "" },
other : { startTime : "", endTime : "" },
}; 对象嵌套在数组中,每个索引代表一周中的某一天。例如,索引1将是星期一。
<tr ng-repeat="hours in businessHours">
<td>Monday</td>
<td>{{hours[0].startTime}}</td>
<td>{{hours[0].endTime}}</td>
<td>{{hours[0].startTime}}</td>
<td>{{hours[0].endTime}}</td>
<td>{{hours[0].startTime}}</td>
<td>{{hours[0].endTime}}</td>
</tr>
我创造了一个小提琴来提供更好的画面
`http://jsfiddle.net/yu216x5w/4/`
答案 0 :(得分:2)
您可以尝试这样的事情:
var hours = [
{
"name" : "Monday",
"hours": {
"sales" : { startTime : "5", endTime : "6" },
"service" : { startTime : "2", endTime : "3" },
"accounting" : { startTime : "4", endTime : "6" },
"parts" : { startTime : "10", endTime : "11" },
"bodyShop" : { startTime : "3", endTime : "8" },
"other" : { startTime : "a", endTime : "b" }
}
},
{
"name" : "Tuesday",
"hours": {
"sales" : { startTime : "5", endTime : "6" },
"service" : { startTime : "2", endTime : "3" },
"accounting" : { startTime : "4", endTime : "6" },
"parts" : { startTime : "10", endTime : "11"},
"bodyShop" : { startTime : "3", endTime : "8" },
"other" : { startTime : "a", endTime : "b" }
}
}
];
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify(hours));
var app = angular.module('myApp', []);
function businessHours($scope, $http) {
$scope.schedule = [];
$scope.loadHours = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
console.log(data);
$scope.schedule = data;
});
};
}
with:
<div ng-app="myApp">
<div ng-controller="businessHours">
<p> Click <a ng-click="loadHours()">here</a> to load data.</p>
<table>
<tr>
<th></th>
<th style="vertical-align:top" scope="col" colspan="2">Sales</th>
<th style="vertical-align:top" scope="col" colspan="2" >Service</th>
<th style="vertical-align:top" scope="col" colspan="2">Parts</th>
<th style="vertical-align:top" scope="col" colspan="2">Accounting</th>
<th style="vertical-align:top" scope="col" colspan="2">Body Shop</th>
<th style="vertical-align:top" scope="col" colspan="2" >Other</th>
</tr>
<tr ng-repeat="day in schedule">
<td>{{day.name}}</td>
<td>{{day.hours.sales.startTime}} - {{day.hours.sales.endTime}}</td>
<td>{{day.hours.service.startTime}} - {{day.hours.service.endTime}}</td>
<td>{{day.hours.accounting.startTime}} - {{day.hours.accounting.endTime}}</td>
<td>{{day.hours.parts.startTime}} - {{day.hours.parts.endTime}}</td>
<td>{{day.hours.bodyShop.startTime}} - {{day.hours.bodyShop.endTime}}</td>
<td>{{day.hours.other.startTime}} - {{day.hours.other.endTime}}</td>
</tr>
</table>
</div>