Incrementing and decrementing a variable within the scope in AngularJS

Objective: When the next/previous button is clicked, the label on the current slide should change to display the next/previous category. View the Category Slider Wireframe for reference.

Context: I previously tried a solution called 'Obtain Next/Previous Value from Object' which required using ng-repeat. However, despite generating the desired data, it did not work properly with the bxSlider plugin as expected. This led me to explore alternative solutions where I can keep the arrows and labels outside of ng-repeat.

Proposed Solution: I realized that keeping this functionality outside of ng-repeat might be the best approach. To achieve this, I believe I need to create a variable attached to the scope that will increment/decrement accordingly. This way, the appropriate Next/Previous buttons can be displayed correctly.

I initially attempted using

ng-click="activeCat = activeCat + 1"
, but this only ended up adding numbers at the end of the category instead of functioning as intended. Any assistance on this matter would be highly appreciated :)

HTML Code snippet

        <!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class="btn btn-next" id="next" ng-click="nextCat = nextCat + 1"> 
                    {{ employees[getNextCategoryIndex($index)].category }} {{nextCat}}
                </a>
            </div>
            <div class="prev-container">
                <a href="" class="btn btn-prev" id="prev">
                    {{ employees[getPrevCategoryIndex($index)].category }} {{prevCat}}
                </a>
            </div>
        </div>
        <!-- END Next & Previous Buttons -->

Controller Logic:

var personControllers = angular.module('personControllers', ['ngAnimate']);

//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http', 
function($scope, $http) {

    $http.get('../static/scripts/data2.json').
    success(function(data) {
        console.log("JSON file loaded");
        console.log(data);
        $scope.employees = data;

        $scope.activeCat = data[0].category;
        $scope.nextCat = data[0 + 1].category;

        //$scope.prevCat = data[0 - 1].category;

    }).
    error(function(){
        console.log("JSON file NOT loaded");
    });

}]);

JSON Data Structure:

[
  {
    "category": "Technology",
    "shortname": "tech",
    "icon": "fa-desktop",
    "cat_id": 0,
    "cards": [
      {
        "id": "card-1",
        "name": "George Sofroniou",
        "shortname": "G_Sof",
        "age": "23",
        "company": "Pirean Ltd.",
        "role": "Graduate UI Developer"
      },
      {
        "id": "card-2",
        "name": "Steve Jobs",
        "shortname": "S_Jobs",
        "age": "56 (Died)",
        "company": "Apple Inc.",
        "role": "Former CEO"
      }
    ]
  },
  {
    "category": "Motors",
    "shortname": "mot",
    "icon": "fa-car",
    "cat_id": 1,
    "cards": [
      {
        "id": "card-1",
        "name": "Elon Musk",
        "shortname": "E_Musk",
        "age": "43",
        "company": "Tesla Motors",
        "role": "CEO"
      },
      {
        "id": "card-2",
        "name": "Henry Ford",
        "shortname": "H_Ford",
        "age": "83 (Died)",
        "company": "Ford Motor Company",
        "role": "Founder"
      }
    ]
  },
  {
    "category": "Football",
    "shortname": "foot",
    "icon": "fa-futbol-o",
    "cat_id": 2,
    "cards": [
      {
        "id": "card-1",
        "name": "Sir Alex Ferguson",
        "shortname": "A_Fer",
        "age": "73",
        "company": "N/A",
        "role": "Retired"
      },
      {
        "id": "card-2",
        "name": "Bobby Moore",
        "shortname": "B_Moor",
        "age": "51 (Died)",
        "company": "N/A",
        "role": "Footballer"
      }
    ]
  },
  {
    "category": "Law",
    "shortname": "law",
    "icon": "fa-gavel",
    "cat_id": 3,
    "cards": [
      {
        "id": "card-1",
        "name": "Harvey Specter",
        "shortname": "H_Spec",
        "age": "43",
        "company": "Pearson Specter Litt",
        "role": "Name Partner"
      },
      {
        "id": "card-2",
        "name": "Saul Goodman (James Morgan McGill)",
        "shortname": "S_Good",
        "age": "48",
        "company": "Better Call Saul",
        "role": "Criminal Defence Attorney"
      }
    ]
  }
]

Answer №1

To organize the data of each object, you can store them in an array and adjust the index incrementally based on the button pressed.

var i = 0
    $scope.dataArray = [];

//populate the array with data
$scope.next = function () {
    i++
};
$scope.prev = function () {
    i--
};

For example: http://plnkr.co/edit/SVXhxvwJqnO8Uarjkxx2?p=preview

GSof Edit:

//Next & Previous Button Category Label
    $scope.i = 0;
    $scope.j = $scope.employees.length;
    $scope.nextCat = $scope.i + 1;
    $scope.prevCat = $scope.j - 1;

    $scope.getNext = function(){
        //console.log($scope.nextCat);
        $scope.nextCat++;
        if( $scope.nextCat >= $scope.employees.length ){
            $scope.nextCat = 0;
        }

        $scope.prevCat++;
        if( $scope.prevCat >= $scope.employees.length ){
            $scope.prevCat = 0;
        }

    };

    $scope.getPrev = function(){
        //console.log($scope.nextCat);
        $scope.prevCat--;
        if( $scope.prevCat < 0 ){
            $scope.prevCat = $scope.employees.length - 1;
        }

        $scope.nextCat--;
        if( $scope.nextCat < 0 ){
            $scope.nextCat = $scope.employees.length - 1;
        }
    };

This condition ensures that when the end of the array is reached, the item will cycle back to the beginning. Both the next and previous buttons now update simultaneously, maintaining their alignment with each other upon button press.

Once again, thank you for your assistance.

Answer №2

Clicking on the ng-click event will trigger a function that increments something.

Here's an example:

<a href="" class="btn btn-next" id="next" ng-click="increment()">

And in the controller JavaScript file:

$scope.increment=function(){
       $scope.flag=false;
    angular.forEach($scope.employees,function(employe){
             if(flag){
                  $scope.nextCat = employe.category;
                  return;
              }
             if($scope.nextCat === employe.category){
                  flag=true;
              }
     });

    }

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

Only show the directive methods when using "ng-if"

I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...

`The Issue with Ineffective Slider Removal`

Below is the complete code: import React, { Component } from "react"; import "./App.css"; import Slider from "@material-ui/core/Slider"; import Typography from "@material-ui/core/Typography"; class App extends Compo ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

Creating a custom filter: How to establish seamless interaction between a script and a node application

I am currently working on implementing a filter feature for a blog using a node express/ MongoDB/Mongoose setup. My goal is to add the 'active' class when a filter is clicked, and then add that filter to an array (filterArray). I want to compare ...

A method to apply a class to the third <li> element using javascript

Can someone help me figure out how to add a class to the third element using Javascript? Here is the structure I am working with: <ul class="products-grid row four-columns first"> <li class="item"></li> <li class="item"></li&g ...

Simplifying JSON structure using C#

I have a json-object in C# (represented as a Newtonsoft.Json.Linq.JObject object) and I need to convert it into a flattened dictionary format. Let me illustrate with an example: { "name": "test", "father": { "name": "test2" "age" ...

Querying Denormalized Data in AngularFire 0.82: Best Practices and Strategies

I have a question that is related to querying denormalized data with AngularFire. I am looking for a solution specifically using AngularFire (current version 0.82). Here is an example of the data structure I am working with: { "users": { "user1": { ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Getting data from a URL using Node.js and Express: A beginner's guide

Currently, I am facing an issue with extracting the token value from the URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. My get request successfully validates the token and redirects the user to a password reset screen. Howe ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Searching for mobile WiFi preferences through a web browserHere are the steps to

Is there a method to access mobile connectivity settings through a website? I am interested in determining the connection type (3G\4G\WiFi) and if it is WiFi, identifying the security method being used. Is this achievable? If so, how? Edit: If ...

A guide on transferring JSON information via a POST request with C#

Looking to send JSON data in a POST request using C#? I've experimented with a few methods but encountered numerous challenges. I'm trying to make the request with a raw JSON string as well as JSON data from a separate file. How would one go ab ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

Retrieving the hidden field value using JavaScript on the server side

I'm encountering an issue with asp:hiddenfield where, after changing its value on the client side and trying to retrieve it on the server side, it returns null. Here is my client-side code: function pageLoad() { var gV = $('#<%=Hidden ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

PHP error: Unexpected non-whitespace character in JSON parsing

I am facing a challenge with displaying a large amount of DB data using PHP/SQL. It takes too long and the result is too big to show all at once. Therefore, I decided to use AJAX to display the data. However, when I tried encoding the data to JSON in my P ...

Utilize PHP to open a JSON string file and then convert it into an array

<?php $postcode=$_POST['script']; $myfile = '{ "1": { "Brand":"MITSUBISHI HEAVY INDUSTRIES, LTD.", "Model_No":"SRK20ZMXA-S / SRC20ZMXA-S", "C.Power_Inp_Rated":0.35, "H.Power_Inp_Rated":0.45, "KWH":1881.95, "Cost":564.585}, "2": { "Br ...

Error: Cannot serialize object of type 'bytes' to JSON format

Recently delving into Python programming, I decided to utilize scrapy in order to create a bot. However, a challenge arose as an error stating "TypeError: Object of type 'bytes' is not JSON serializable" appeared when attempting to run the projec ...

Choose the total and categorize by type

Currently working on populating a data array for a Morris Chart using data from my MySql Database. The table 'buchungen' has the following structure: ID Value Kind Date 1 200 L 2016-01-01 2 250 B 2016-01-01 3 25 ...