我正在开发一个应用程序,我应该通过http.get方法从服务器中检索一个JSON数组。
数组的结构如下:
[{
"day": "17/11/2016",
"time": "09:45"
}, {
"day": "17/11/2016",
"time": "16:50"
}, {
"day": "18/11/2016",
"time": "11:25"
}, {
"day": "18/11/2016",
"time": "12:30"
}, {
"day": "21/11/2016",
"time": "16:10"
}, {
"day": "21/11/2016",
"time": "17:25"
}]
从这个阵列我应该创建一个表格,其中有两个选择在第一天我们(例如2016年11月17日,2016年11月18日,2016年11月21日),在第二个我应该有时间“属于”天(例如09:45,16:50或11:25,12:30或16:10,17:25)。
我认为我已经找到了这个问题的解决方案但是当我试图运行项目时,选择总是空的,但控制台告诉我没有错误。
这是我的代码,
HTML :
<html>
<head>
<script data-require="angular.js@1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div class="form-group">
<label>Event Date</label>
<select ng-options="event as event.date for event in ctrl.data.events" ng-model="ctrl.event">
<option value="">Select</option>
</select>
</div>
<div class="form-group">
<label>Event Time</label>
<select ng-options="schedule as schedule.time for schedule in ctrl.data.schedules | filter: { date: ctrl.event.date}" ng-model="ctrl.schedule" ng-disabled="!ctrl.event">
<option value="">Select</option>
</select>
</div>
</div>
</div>
</body>
</html>
JS :
angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService'];
function DefaultController(dataService) {
var vm = this;
getEvents();
function getEvents() {
return dataService.getEvents()
.then(function (data) {
vm.data = data;
return vm.data;
});
}
}
dataService.$inject = ['$http'];
function dataService($http) {
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json; charset=utf-8" && angular.isString(data)) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
return result;
} else {
return data;
}
}
};
return $http.get('events.json', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
有人可以帮助我吗?
Than'ks