Reputation: 2012
I am dynamically creating an object on a web app using AngularJS. The idea is that the user can load new events as they click a button, for this to work I need to get the date of the last one so Ill know which ones to load next.
This is the code that generates the JSON object
services.getEvents().then(function(data){
$scope.events = data.data;
});
and my html...
<li ng-repeat="event in events | orderBy:'-event_date' ">
<span>{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
</li>
An example of one event...
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
Is it possible to extract the latest date from a list of these so I can send it back to the API? Or am I going about this a wrong way altogether.
Im also using this an opportunity to learn AngularJS
Upvotes: 1
Views: 1607
Reputation: 16498
var app = angular.module("app", []);
function MainCtrl ($filter) {
this.data = [
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-05-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
},{
"event_id":"2",
"event_name":"Event 1",
"event_date":"2015-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
},{
"event_id":"3",
"event_name":"Event 1",
"event_date":"2014-9-27 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
];
this.lastOne =$filter('orderBy')(this.data,'-event_date')[this.data.length-1].event_date ;
}
angular.module("app").controller("MainCtrl", MainCtrl);
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="MainCtrl as vm">
<div class="container">
<h3>Latest One:{{vm.lastOne}}</h3>
</div>
</body>
</html>
Upvotes: 1
Reputation: 738
If you make your server side code return an array sorted by descending date, you could just take the date off the first item in your array. Something like:
events[0].event_date;
Failing that, you could do the sorting on the client side with something like:
events.sort(function(a, b){return new Date(a.event_date) < new Date(b.event_date);});
Then get the value of:
events[0].event_date;
Upvotes: 0
Reputation: 162
To access the last element of an array use length -1
events[events.length - 1].event_date
if the response from the server is not sorted in any way you should filter first
var sortedArray = $filter('orderBy')($scope.events, '-event_date');
var lastDate = sortedArray[sortedArray.length - 1].event_date
hope this gets you on the way.
Upvotes: 1