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

"Splitting a DOMNodeList into an array of chunks using PHP

I am attempting to utilize an array chunk function with a DOMNodeList. Unfortunately, this is resulting in an error message as the DOMNodeList does not conform to the standard PHP array format. Below is the code snippet causing the issue: foreach (array_c ...

What could be the reason why readyState is not equal to 4?

I've been trying to figure out how to use Ajax to fetch data from a database, but I'm encountering some issues... The problem arises when I submit the query and nothing appears on the screen... I understand that this issue is related to the read ...

Requesting data asynchronously using AJAX and displaying the filtered results on a webpage using JSON

When I send a request to my node.js server for a .json file containing person information (first name, last name), I want the data to be filtered based on user input. For example: When I request the .json file from the server, it gives me a list of people ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

The event for 'deviceready' in Cordova is not getting triggered when placed inside the angular .run block

Recently, I've been facing difficulties in getting 'deviceready' to register within AngularJS. It was functioning properly earlier, so I'm puzzled about what might have altered. If I trigger 'deviceready' from a global addEve ...

Reduce the density of x-axis labels in highcharts

Do you have any input on Highcharts? This chart belongs to me: I am looking to reduce the density of x-axis labels, similar to the y-axis. Your assistance is greatly appreciated. Edit: for instance, take a look at this example: http:// jsfiddle.net /vu ...

An advanced template system incorporating dynamic scope compilation

My project requires a unique solution that cannot be achieved with standard data-binding methods. I have integrated a leaflet map that I need to bind with a vue view-model. While I was able to display geojson features linked to my view, I am facing chall ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Store Form Input as JSON Data File

Seeking advice on the optimal method to save submitted form data to a separate file called data.json, for future reference. The form layout is quite basic: <form> <fieldset> <label for="name">Name:</label> &l ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

What is the proper method for effectively employing destructuring?

I'm trying to figure out how to properly return state with a fetched array using the spread operator. Here is my reducer code snippet: function themes(state = [], actions){ switch(actions.type){ case FETCH_THEMES_SUCCESSFULLY: const { th ...

Issues with loading JSON data through JQuery

I am completely new to the process of loading JSON text using JavaScript or JQuery. JSON is a new concept for me as well. Currently, I have PHP providing me with some JSON text containing images stored on my server in the following format: [ [{ ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

deleting an object from an array in JavaScript

I have a collection of objects that looks like this: [{ "id": 2, "price": 2000, "name": "Mr Robot T1", "image": "http://placehold.it/270x335" }, { "id": 1, "price": 1000, "name": "Mr Robot T2", "image": "http://placehold.it ...

Performing mathematical operations in JavaScript, rounding to the nearest .05 increment with precision up to two

Apologies in advance. After reviewing multiple posts, it seems like the solution involves using the toFixed() method, but I'm struggling to implement it. $('.addsurcharge').click(function() { $('span.depositamount&ap ...

Can $location be modified without triggering its corresponding $route?

Can you update the location path in Angular.js without activating the connected route? For example, is there a way to achieve this (see pseudo code below): $location.path("/booking/1234/", {silent: true}) ...

Vows.js: Utilizing data from parent topics in nested topics

Is there a way to access the return value of an outer topic from within a test in an inner topic? To clarify, consider this example: "build.css" : { topic : function(file) { fs.readFile(fixtures + "/public/build.css", "utf8", this.callback); }, ...

Store information during each iteration

Below is a snippet of my JavaScript code: for (var i in data){ var trans_no = data[i]; var transno = trans_no.transno; var transdate = trans_no.transdate; var dropno = trans_no.drop; var cusname ...

Is there a way to utilize Javascript/JQuery to access and interpret PHP-generated HTML form data in a multi-dimensional array format?

I am having difficulty in reading and manipulating data from an HTML form using Javascript/JQuery. Situation: I have a sales screen displaying multiple products, and I aim to iterate through them all, analyze their contents, and showcase some of the data ...