"Implementing reverse cycling functionality in an AngularJS carousel using the modulo operation

I am currently working on creating a carousel component using AngularJS inspired by this particular example that I stumbled upon on stackoverflow.

The next function is functioning correctly, but when attempting to implement the previous function, it starts cycling into negative values once it reaches 0, going all the way to -3 before jumping back to 0.

Could someone provide an explanation of what % $scope.pages.length exactly does and how it operates? I attempted to search online for answers but could not find any comprehensive explanations.

This is my controller:

.controller('portfolioController', function($scope) {
    $scope.pages = [
    {
        image: "/../images/Placeholder.jpg",
        alt: "thumbnail first page",
        name : "1",
        description : "My First Webpage",
        active : 1
    },
    {
        image: "/../images/Placeholder.jpg",
        alt: "thumbnail first page",
        name : "2",
        description : "My Second Webpage",
        active : 0
    },
    {
        image: "/../images/Placeholder.jpg",
        alt: "thumbnail first page",
        name : "3",
        description : "My Third Webpage",
        active : 0
    },
    {
        image: "/../images/Placeholder.jpg",
        alt: "thumbnail first page",
        name : "4",
        description : "My Fourth Webpage",
        active : 0
    }
    ];
    $scope.current = 0;
    $scope.Next = function() {
        $scope.current = ($scope.current + 1) % $scope.pages.length;
    }
    $scope.Previous = function() {
        $scope.current = ($scope.current - 1) % $scope.pages.length;
    }
});

This is my html:

<div class="col-xs-12">
        <div class="thumbnail">
            <img ng-src="{{ pages[current].image }}" alt="{{ pages[current].alt }}">
            <div class="caption">
                <h3>{{ pages[current].name }}</h3>
                <p>{{ pages[current].description }}</p>
            </div>
        </div>
        <div class="row carousel-thumbnails">
            <div class="col-xs-12">
                <div class="btn btn-info" ng-click="Previous()">Previous</div>
                <img ng-repeat="img in pages" ng-class="{'active': img.active}" src="{{ img.image }}" alt="{{ img.alt }}">              
                <div class="btn btn-info" ng-click="Next()">Next</div>
            </div>
        </div>
    </div>

Answer №1

The operation in question is known as a modulo or remainder calculation. Essentially, it divides the first value by the second and provides the remaining amount.

If you're wondering why your $scope.Previous variable isn't functioning properly, it's likely due to it returning negative figures once it hits zero instead of looping back to the maximum value (which should be $scope.pages.length - 1). To resolve this issue, consider implementing something like the following using the ternary/conditional operator:

$scope.current = $scope.current == 0 ? ($scope.pages.length - 1) : ($scope.current - 1)

To see this in action, check out this live demo on jsfiddle.

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

JAWS interpreting inaccessible span element

I'm currently working on AngularJS code that dynamically enables a radio button within a span. `<span data-ng-if="(!object.enabled || (form && !form.enabled))" class="rf-visuallyhidden"> Disabled</span> ` Durin ...

Getting the data stored in variables from a JavaScript file into Python

Currently, I am facing a challenge with a JavaScript file where I need to extract data in a specific format. My goal is to make the data readable and subscriptable similar to a Python dictionary (like dict["key/value"]). When I try opening the file, it re ...

Responsive Bootstrap table unable to expand div upon clicking

My bootstrap responsive table has a unique functionality that allows specific divs to expand and collapse upon button click. While this feature works seamlessly in desktop view, it encounters issues on mobile devices. CSS .expandClass[aria-expanded=true] ...

The background color disappears when viewed on mobile devices

I have created a table using HTML and CSS. The issue is that the background colors of the table display correctly on a desktop, but on a mobile phone, they appear completely transparent while the text remains visible. I am using Bootstrap 4 for this websi ...

Encountered an issue while integrating Firebase with a provider

I am currently working on integrating Firebase into a provider to set the baseURL in the app configuration. I have ensured that all required files are included, injected the Firebase provider, and defined the Firebase dependency. Any assistance with this w ...

Positioning CSS for a Responsive Button

Currently, I am working on making my modal responsive. However, I am encountering an issue with the positioning of the "SAVE" button. The button is not staying in the desired position but instead disappears. Below is the snippet of my HTML and CSS: .dele ...

Exploring Nested Objects in ReactJS

When I make a call to , I am able to access properties such as active_cryptocurrencies and active_markets, but for some reason, total_market_cap and total_volume_24h are returning as undefined. import React, { Component } from "react"; import { render } f ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...

Creating Javascript objects using provided JSON data

Good day! I am looking for assistance in understanding how to create objects from JSON data that has been provided: { "type":"FeatureCollection", "features":[ { "type":"Feature", ...

Error: The specified file or directory does not exist at location 'D:E-commerceJsfrontend ode_modules.axios.DELETE'

As I work on my e-commerce project using vanilla JavaScript and webpack with npm, I keep encountering an issue while trying to install axios. npm ERR! enoent ENOENT: no such file or directory, rename 'D:\E-commerceJs\frontend\node_mod ...

Hold off on addressing the nested loops within a TypeScript subscription

Goal: Ensure all nested loops complete processing before returning final value. Problem: Final value returned prematurely, before completion of loop processing. In the code snippet below, I am sending paramListToComplete to a data service for creating a ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Incorporating data retrieved through AJAX requests into a Python function

The Flask application described below continuously makes Ajax calls to a backend index function that queries a database and injects the results into a template. However, the injected data is not being refreshed after the Ajax calls are completed, leading ...

Binding ngModel to a method within $scope in Angular

Not really a question with code, but more for my clarification. Please excuse me if this isn't the appropriate place to ask... I was experimenting with a basic checkbox that had an ngModel assigned to it: <input type="checkbox" ng-model="someFlag ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

What is the best way to access Dynamic Array Data within a nested ng-repeat loop?

Dealing with JSON data that is deeply nested with strings and arrays, I am attempting to assign a true or false value for each day. Below is how I achieved this without a nested array: No Nested Array(Codepen 1) Here's the HTML: <ion-toggle ng-r ...

Update the text in the textarea using jQuery or JavaScript

I have incorporated gridster widgets into my webpage, each with multiple images and a textarea. The textarea contains links to the images separated by commas, initially populated from JSON. Users can delete images from the grid, and I want the textarea con ...

steps for setting up an endless scroll masonry grid

I have incorporated masonry js to display content on my website. Now, I am interested in adding infinite scrolling functionality using this script. I came across a demo that showcases this feature. However, I am struggling to figure out how to implement ...

How to reset the width of custom-sized table columns in a prime-ng p-table

Is there a method to reset the column widths of a p-table in primeng that have been set with 'resizableColumns="true"'? I want to provide users with the ability to revert back to the original sizes. ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...