Retrieve the unshifted elements from the array and display them using AngularJS

Greetings, everyone! I am currently working on a shopping cart list that only displays three items at a time. To achieve the scrolling effect and shift the displayed items by one, I have implemented the javascript protocol shift. By using push, I transfer the shifted items into a new array. While this method successfully adds new items to the list, it does not scroll back to display the previous items. You can view my progress so far on jsfiddle or visit the live site at live site

(function(){
var app = angular.module("moxierevere",['ngCart']);
app.filter('myFilter', function () {
    return function (items, count) {
        var result = [];
        for (var i = 0; i < items.length && result.length < count; ++i) {
            if (items[i].available > 0) result.push(items[i]);
        }
        return result;
    };
});
app.controller("ItemsController",['ngCart', '$scope', function(ngCart, $scope){

ngCart.setTaxRate(0.00);
ngCart.setShipping(2.99); 
this.items = allItems;
$scope.itemsPerListing = 3;
var shifteditem = [];
var shifteditems = [];

 $scope.nextPage = function () {
  this.items = allItems;
    if($scope.itemsPerListing >= this.items.length)
    {
        $scope.itemsPerListing =  this.items.length;
    }
    else
    {
    shifteditem.push( $scope.items.shift());
    console.log(shifteditem);
    }   
  };

$scope.prevPage = function() {
this.items = allItems;
shifteditems.unshift(shifteditem);
console.log( shifteditems);

};
}]);
var allItems = [
{
id:0,
name: "item1",
image: "http://dreamcpu.com/moxierevere/images/br.JPG" ,
price: 2.00,
available: 10,
size: "S , M, L"
},
{
id:1,
name: "item2",
image: "http://dreamcpu.com/moxierevere/images/avacados.JPG" ,
price: 5.00,
available: 10,
size: "S , M, L"
},
{
id:2,
name: "item3",
image: "http://dreamcpu.com/moxierevere/images/chicha.JPG" ,
price: 2.00,
available: 3,
size: "S , M, L"
},
{
id:3,
name: "item4",
image: "http://dreamcpu.com/moxierevere/images/lomo.JPG" ,
price: 6.00,
available: 4,
size: "S , M, L"
},
{
id:4,
name: "item5",
image: "http://dreamcpu.com/moxierevere/images/satuna.JPG" ,
price: 2.00,
available: 5,
size: "S , M, L"
},
{
id:5,
name: "item5",
image: "http://dreamcpu.com/moxierevere/images/satuna.JPG" ,
price: 2.00,
available: 5,
size: "S , M, L"
},
{
id:6,
name: "item5",
image: "http://dreamcpu.com/moxierevere/images/satuna.JPG" ,
price: 2.00,
available: 5,
size: "S , M, L"
}
];  
})();

Answer №1

Instead of removing the items from the array, it's better to work with the scroll index and create a new scope variable containing just 3 items at a time. Use your scroll buttons to modify a $scope.index variable accordingly.

$scope.$watch('index', function(newVal, oldVal){
    $scope.displayedItems = [$scope.items[newVal], $scope.items[newVal + 1], $scope.items[newVal + 2] ];
});

This setup will watch the index changes and update the displayed items accordingly.

Answer №2

Success achieved by implementing shift and unshift methods to make it work. Still in the process of managing the counter for correct index handling, but current functionality is satisfactory.

$scope.nextitem = function () {
  this.items = allItems;
    if($scope.itemsPerListing >= this.items.length)
    {
        $scope.itemsPerListing =  this.items.length;
        console.log($scope.itemsPerListing);
    }
    else
    {
    shifteditem.push( $scope.items.shift());
    counter = shifteditem.length;
     console.log(this.items.length);
     if (counter > $scope.itemsPerListing)
     {
         counter  = this.items.length + 2;

     }
    }        
  };

$scope.previtem = function() {
this.items = allItems;

if(counter > 0){
    $scope.items.unshift(shifteditem[counter-1]);
    counter = counter - 1;
    console.log(counter);
}   
};
}]);

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

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Display the name provided in a registration form on the confirmation page as a token of appreciation

I'm attempting to display the user's entered name in a Mailchimp form (where the name value is FNAME) on a custom thank you page (e.g. "Thank you NAME HERE,"). I haven't found a way to do this using Mailchimp's documentation other than ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Allow the select option to be clicked, while preventing it from automatically filling the select input field in reactstrap's Input component

I have a select with an option called "+ Create new" When the user clicks on this option, I am displaying a modal to create a new option. However, I do not want this select option to show "+ Create new" after it is clicked. How can I make the o ...

Error message encountered: Module not found. It may not have been loaded yet

I am encountering an issue while attempting to utilize an npm module in my VUE component. I have imported the module and defined the necessary methods, but I am receiving the following error: Uncaught Error: No such module. (Possibly not yet loaded) De ...

Ways to Extract HTML DOM Attributes using Jquery

I am working with an HTML DOM that is saved in a JavaScript Variable. I need to figure out how to retrieve its attributes. For example: <script> //element_html is ajax response var element_html = '<h1 style="" class="app-control " data-order ...

Guide on correctly importing a node module, ensuring all functions are exported

I am facing an issue with my file stats.js. Upon inspecting its contents, I found the following code: (function () { func1 = function () { } func2 = function () { } module.exports = this; }).call(this); According to what I have r ...

AngularJS Custom Navigation based on User Roles

I am currently developing a small web application using angular. My goal is to implement role-based navigation in the app. However, I am facing an issue where the isAdmin function does not seem to be getting called on page load, resulting in only the foo a ...

CSS personalized by the user

I want to develop an application that allows users to input their customized CSS, which will then be implemented on the webpage. Is there a straightforward method to achieve this, or do I need to manually parse and modify the CSS by accessing elements like ...

Should I convert to an image or utilize the canvas?

I'm debating whether it's more efficient to convert a canvas drawing into an image before inserting it into the DOM, or if it's better to simply add the canvas itself. My method involves utilizing canvas to generate the image. ...

Implementing a pull-to-refresh feature in React Native using Redux

I need to implement pull to refresh functionality, but I'm unsure of what to call from _Refresh(). My actions, constants, and reducers are stored on another page. How can I trigger the API again? Thank you in advance for your assistance. class Homewo ...

Node.js - Implementing URL Validation for User Input

I've been utilizing the node module 'request' to develop a job queue for retrieving HTML data from a URL entered by a user. Here's the current state of my code: var jobQueue = []; function processNextJob() { if (jobQueue.length &l ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

AngularJS - Unexpected events are triggered on the parent window when clicking in a new browser window where a controller is open

Trying to implement a requirement for an audit log page with a button that opens logs in a new browser window while continuing other activities on the main application. Utilizing ui-router and angularjs (1.6), here is the code snippet - Controller Route - ...

Exploring the application of URL parameters in HTML code

How can I use URL parameters retrieved with Javascript in my HTML? <script> var url_string = window.location.href; //window.location.href var url = new URL(url_string); var c = url.searchParams.get("name"); console.log(c); </script> I am tryi ...

Using an AJAX post request to retrieve the HTML content

I'm grappling with an AJAX function and a processor.php script. Here's the code snippet: $.ajax({ url: "processor.php", type:"POST", data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" ...

"Unexpectedly, the original values of an array were altered by a Javascript

After creating a constructor function to generate an object, I set up an array named arr1 with initial values. Next, I use the map function on arr1 to create a new array called arr2. However, I noticed that the original arr1 was altered. Could this be du ...

Error: Openshift's Node.js module is unable to locate the module "mosca"

We encountered an issue when trying to include mosca = require("mosca") in our server.js script. Any advice on how to resolve this error would be greatly appreciated. ^ Error: Cannot find module 'mosca/index.js' at Function.Module._ ...