Building a navigation system with previous and next buttons by implementing JavaScript

I am currently working with AngularJS and I have data that is being received in the form of an array containing two objects. As a newcomer, I am still trying to figure this out.

data[
{
"something":"something1",
"something":"something1",
"something":"something1",
},
{
"something":"something2",
"something":"something2",
"something":"something2",
}
]

My goal is to create previous and next buttons that, when clicked, will transition from the first object to the second object. I am aware that by using:

current = response.data[0];

I can access the first object in the array. I attempted code similar to this:

   var current = 1
  const getSessions = () => {
    loginService.getUser().then((response) => {
      var user_id = response.data.id;
      console.log("getUser returning this => ", response.data);
      loginService.getUserSessions(user_id).then((response) => {
        current = response.data[0];
        $scope.sessions = response.data;
      })
    })
  };

 getSessions();

  $scope.nextPage = function() {
    current++;
    getSessions();
}
$scope.prevPage = function (){
    if(current > 1){
        current--;
    getSessions();    
    }
}

However, I am still uncertain about the best approach to take.

Answer №1

To resolve the issue, it is recommended to update your counter by incrementing/decrementing it and then setting the current session to the currentIndex in the sessions array. Although I have not run a test on this code, I believe these modifications will be beneficial.

    var current;
    var currentIndex = 0;

    const getSessions = () => {
     loginService.getUser().then((response) => {
      var user_id = response.data.id;
      console.log("getUser returning this => ", response.data);
      loginService.getUserSessions(user_id).then((response) => {
        $scope.sessions = response.data;
        current = $scope.sessions[0]
      })
     })
    };

    getSessions();

    $scope.nextPage = function() {
      if ( currentIndex < ($scope.sessions.length - 1) ) {
        currentIndex++;
        current = $scope.sessions[currentIndex]
      }
    }

    $scope.prevPage = function (){
      if ( currentIndex > 0 ) {
        currentIndex--;
        current = $scope.sessions[currentIndex]
      }
    }

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

Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this. The issue arises because the PDF path is generated dynamically at runti ...

Price Adjuster Tracker

Recently, I coded a small JavaScript program with the purpose of: incrementing or decrementing the quantity of an item by 1 adjusting the price of an item based on the initial price However, my excitement turned to disappointment when I encountered these ...

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...

When using Foreach-Object, an error is generated stating 'cannot index into a null array', however, the issue is resolved when manually copying each line of the loop

I have been working on a script that revolves around the concept of organizing arrays into hash tables, and then iterating through them using foreach-object $_ index to execute commands or generate output with minimal redundant code. Despite numerous atte ...

JavaScript has received an event on Server XHR

Situation: There is a scenario where the target API is external and cannot be altered. A JS client initiates sending data to the API upon clicking a button. The code snippet resembles something like this: $.ajax({ type: "POST", url: &quo ...

Issue with Angular UI tooltip not closing correctly inside ng-repeat loop

Check out the plunker link provided below for reference: http://plnkr.co/edit/RPpjULZsSDnTFPKiafl2 Essentially, I am experiencing an issue where the angular-ui tooltip persists even when moving to a position with ng-disabled set to true. Any suggestions ...

I am interested in retrieving all users along with the places they have created using virtual population

const fetchAllUsers = async (request, response) => { try { await User.find({}).populate('place').exec(function(err, data) { console.log(data.places) console.log(data) res.json(&quo ...

How can I utilize JQ to display two specific objects located within an array in a JSON file?

My Json file begins with two objects containing description and rtmp_url details. I am striving to extract only these two fields. { "features": [ { "type": "Feature", "geometry": ...

React useEffect not working when using the default state

I'm currently facing an issue where setting the page to its default value from the refresh function does not trigger the useEffect hook on the first attempt. However, if I run the refresh function for the second time, it works fine. Interestingly, thi ...

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

"Exploring the world of AngularJS Datepicker alongside the power

My desire is to have a calendar that displays only the option of selecting a month and year, with the format being displayed as "yyyy-mm". Once the month and year are selected, I need it to update the ng-model variable value in the specified format. I&apos ...

What is the best way for me to implement a .config feature to allow for customization of my

I have developed a small code library for angular js. Within my library's main module, I have implemented a method called .config that relies on my moduleConfigProvider. I anticipate the user of my library to invoke .configure on my config provider du ...

Querying a MongoDB collection with an array in the table

I am working with a table called DBLIST and I need assistance in writing the equivalent query for this specific case. select databases.name,databases.host,databases.ha_map from DBLIST where "id"="DB1" and databases.dbrole="Primary"; DBLIST { "_id": "DB ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

How can you verify the anticipated log output in the midst of a function execution with Jest unit testing?

Below is a demonstration function I have: export async function myHandler( param1: string, param2: string, req: Request, next: NextFunction, ) { const log = req.log.prefix(`[my=prefix]`); let res; If (param1 === 'param1&a ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

What is the best way to retrieve all Objects by a specific property in React when working with an array of Objects?

I am looking to create a multiple checkbox filter where selecting the 'Accessories' option will display items with the 'Accessories' value under the 'type' property. However, before I proceed with that, I need to ensure that I ...

Connecting registered users to a database in a Firebase web application

What is the best way to connect authenticated users to my Firebase database within my Angular JS web application? I have already created a "users" node in my database tree to store user data, but I am struggling with how to organize each user's infor ...

How do I create individual tables for each JSON array within my object using React and MaterialUI?

I have a unique challenge with a component that creates multiple tables, all within one <TableContainer>. The issue lies in the fact that every table is confined within the same container and I am unable to customize each table separately. Each tabl ...

How can one ensure that array arguments have the correct dimensions in Python 3?

For my Python 3.7 project as a beginner, I've noticed that many functions require arguments that are numpy.ndarray's representing two-dimensional r x n matrices. The row dimension r is crucial: certain functions need 1 x n vectors while others ne ...