Retrieving the date from the final item in a JSON object using AngularJS

In my web application built with AngularJS, I am dynamically creating objects. The goal is to allow users to load new events by clicking a button. To achieve this functionality, I need to determine the date of the last event loaded so that I can fetch the next ones.

Below is the code snippet responsible for generating the JSON object:

    services.getEvents().then(function(data){
        $scope.events = data.data;
    });

Here's a glimpse at the corresponding 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>

Take a look at an example event from the list:

{
 "event_id":"1",
 "event_name":"Event 1",
 "event_date":"2014-09-26 00:00:00",
 "event_venue":"Limerick",
 "event_description":"stuff"
}

My question is - how can I extract the latest date from these events in order to send it back to the API? Am I approaching this problem incorrectly?

Furthermore, I see this as an opportunity to enhance my understanding of AngularJS.

Answer №1

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


function MainController ($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.latestEvent =$filter('orderBy')(this.data,'-event_date')[this.data.length-1].event_date ;
 }

angular.module("myApp").controller("MainController", MainController);
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="MainController as vm">
  <div class="container">
     <h3>Latest Event Date: {{vm.latestEvent}}</h3>
    
  </div>
 
</body>
  </html>

Answer №2

To retrieve the final element of an array, simply subtract 1 from the length property

elements[elements.length - 1].element_value

If the data received from the server is not organized in any specific order, it is recommended to filter the data before proceeding

var sortedElements = $filter('orderBy')($scope.elements, '-element_date');
var lastElementDate = sortedElements[sortedElements.length - 1].element_date

I trust this information will guide you in the right direction.

Answer №3

To retrieve the latest date from an array sorted in descending order on the server side, you can simply access the date of the first item like this:

events[0].event_date;

If sorting on the server side is not possible, you can achieve the same result on the client side by using the following code snippet:

events.sort(function(a, b){return new Date(a.event_date) < new Date(b.event_date);});

Then, to obtain the latest date value:

events[0].event_date;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Installation of a cloned Parse server

I downloaded the Parse server repository from parse-server-example and set up MongoDB, as well as installed Node.js packages using npm install. However, when I try to start the app with npm start, I encounter this error in the terminal!! How can I resolve ...

Display a JavaScript variable as an attribute within an HTML tag

let disableFlag = ''; if(value.action.length === 0) { disableFlag = 'disabled="disabled"'; } row += '<td><input type="checkbox" name="create" value="1" class="checkbox" data-action="'+ value.action + '" data-co ...

Investigate the dynamic form validation using jQuery

I have set up an input field using jQuery. When the button "add a step" is clicked, jQuery will generate the following structure in the div all_steps: <div class="step"> <div class="header_step">Step '+ (x + 1) +' of the Tutoria ...

Difficulty encountered while transmitting JSON data from Express to React

Currently, I am diving into learning express and facing an issue with transmitting JSON data from my express server to my react application. When working on my express server, I initiate an API call to the openweathermap API and then send the obtained JSO ...

Does the built-in waiting mechanism in Protractor automatically handle promises?

While browsing through Stack Overflow, I stumbled upon this response in a discussion about Protractor tests and asynchronous solutions: 'AFAIK expect waits internally for the related promises.' I have tried looking through the official Protract ...

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

numbered navigation jquery plugin

Can anyone recommend a jQuery plugin or alternative solution for creating a navigation system for comments similar to YouTube? Here is the link for reference: Thank you in advance. ...

Assign a unique ID to each Angular Material checkbox

Presently, I am facing an issue: I am required to generate md-checkboxes from a Database. The implementation is successful using ng-repeat. However, I am encountering difficulties in fetching the data from these checkboxes. Each entry in the Database has ...

Leverage PHP to interpret and update JSON data stored in a file

Currently, I have a JSON data stored in a file named list.txt: { "bgates":{"first":"Bill","last":"Gates"}, "sjobs":{"first":"Steve","last":"Jobs"} } I am seeking guidance on how to include "bross":{"first":"Bob","last":"Ross"} into my file using PHP. Th ...

Invoke a controller in Prestashop by utilizing AJAX technology

I am struggling to figure out how to call the method / function in my controller. The controller is named TestController.php, and I also have files named Test.tpl and Test.js. Additionally, I am unsure of what to put in the URL field. My goal is to retrie ...

Having trouble establishing a connection between data in Databricks and the data lake, as well as reading JSON files into

i'm currently working on a project inspired by the content in this blog post: specifically focusing on section 13 - utilizing Chloropleth maps: the code snippet they provide is as follows: import pandas as pd url = ( "https://raw.githubus ...

Employing asynchronous operations and the power of async/await for achieving seamless integration

I am currently facing an issue where I need to retrieve queries from a database stored in Postgres. A function is utilized, which employs a callback mechanism. In order to fetch rows from the database, there exists a function called getRecipesByCategoryFo ...

Guide on executing MySQL queries in AngularJS with the help of the Laravel 4 framework

I am having issues executing MySql Queries in the Laravel framework using AngularJS. I am currently unable to successfully delete a database record through the button functionality. The existing code is able to insert data into the database, retrieve data ...

pop-up window that shows chosen choices using javascript or ajax

I have a specific HTML code that allows users to select multiple options. I would like these selected options to be displayed in a popup or a div in real-time as the user makes their selections. I have attempted using a selectbox with checkboxes, but extra ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Separating JSON objects by their key value

At the moment, I am focused on retrieving the expiry status of Azure AD applications. I have collected approximately 1700 AD applications and added a new key pair (status) to the JSON object based on the expiration date of the secret. 1) valid 2) Expired 3 ...