我正在构建一个系统,该系统根据使用AngularJS发送到API的日期来获取新事件。我目前仍处于AngularJS的学习阶段,所以我想知道是否有一些我失踪的东西。
我的问题是,即使数据在页面加载时正确加载,当我第一次点击undefined
$scope.newEvents
<ul>
<li ng-repeat="event in events | orderBy:'-event_date' ">
<span >{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
</li>
</ul>
时,即使它已成功获取数据API(我可以在控制台中看到)。
我试图构建一个JSFiddle,但是我无法完成整个工作。
这是html输出......
输出......
var eventApp = angular.module('eventApp', ['ngRoute']);
eventApp.factory("services", ['$http', function($http) {
var apiBase = 'http://example.net/angular-api/'
var service = {};
service.getEvents = function(latest_date){
return $http.get(apiBase + 'events?latest_date=' + latest_date);
}
return service;
}]);
我的js中的get请求......
$scope.events
当页面加载其正常工作时,它会成功发出请求并更新var date = new Date();
$scope.todays_date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
$scope.events = [{}];
services.getEvents($scope.todays_date).then(function(data){
$scope.events = data.data;
});
...
ng-click
但是当点击加载then
函数的按钮时,我的数据未定义。我最初认为日期格式有问题,但它成功获取数据这一事实令我感到困惑。问题始于 $scope.addFiveNew = function (new_or_old) {
if (new_or_old == 'new') {
$scope.latest_date = $scope.getNewestDate();
services.getEvents($scope.latest_date).then(function(data){
$scope.newEvents = data.data;
});
console.log($scope.newEvents);
// update the list (this is currently failing on first click)
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
}
以下......
$scope.getNewestDate = function() {
var sortedArray = $filter('orderBy')($scope.events, 'event_date');
var NewestDate = sortedArray[sortedArray.length - 1].event_date;
return NewestDate;
};
控制器中的此功能创建发送日期...
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
以下是一些数据的示例......
{{1}}
答案 0 :(得分:3)
then
内的位是异步的,所以你的代码的其余部分可以在没有通过返回服务方法更新范围的情况下运行,对吗?
services.getEvents($scope.latest_date)
.then(function(data){ //whenever the service returns
$scope.newEvents = data.data; //update the scope
console.log($scope.newEvents); //log the results
// update the list
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
});
答案 1 :(得分:2)
我认为你的服务上的getEvents调用正在返回一个promise。在promise上调用.then将异步调用传递的函数。那么,你的$ scope.newEvents = data.data;将在该块中的其余语句之后调用。我认为您可以将.then语句更改为以下内容,它应该可以正常工作:
$scope.addFiveNew = function (new_or_old) {
if (new_or_old == 'new') {
$scope.latest_date = $scope.getNewestDate();
services.getEvents($scope.latest_date).then(function(data){
$scope.newEvents = data.data;
console.log($scope.newEvents);
// update the list (this is currently failing on first click)
angular.forEach($scope.newEvents,function(item) {
$scope.events.push(item);
});
});
}
}