Facing an issue with deleting items from the cart in Angular and unable to resolve it

I am trying to figure out how to delete all items added to the cart by clicking on a clear button. I started writing a function for this, but it doesn't seem to be working. I think the issue might be that I forgot to push the items to the cart. How can I accomplish these tasks? If you notice any mistakes, please let me know.

angular.module('TransactionApp', [])
    .controller('TransactionsCtrl', function($scope) {
        $scope.title = 'Add to cart';

        $scope.itemsArray = [{
                price: 50,
                name: "Whey protein",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 60,
                name: "Protein bar",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 35,
                name: "BCAA",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 50,
                name: "Whey protein",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 60,
                name: "Protein bar",
                img: 'img/item-1.png',
                quantity: 0
            },
            {
                price: 80,
                name: "BCAA",
                img: 'img/item-1.png',
                quantity: 0
            }

        ];

        $scope.addTo = function(item) {
            item.quantity += 1;
        }

        $scope.getCost = function(item) {
            return item.quantity * item.price;

        }

        $scope.cart = [];

        $scope.getTotal = function() {
            return $scope.itemsArray.reduce((a, b) => a + b.price * b.quantity, 0);
        }

        $scope.clearCart = function() {
            return $scope.cart.length = 0;
        };
    });

Answer №1

To refresh the elements in the array, simply reset it like this:

   $scope.cart = [];

No need to output any result, you can determine the count by checking the length property.

Answer №2

This is what you need:

function clearTheCart() {
  myShoppingCart = [];
};

Answer №3

If you want to clear it completely, you can do so by using the following method:

$scope.cart = [];

Alternatively, if you wish to remove items one by one:

$scope.cart.slice(start, end);//where 'start' is the index from which you want to start deleting and 'end' is the number of elements to delete.

If you want to add an item to the array at the last index, you need to use the push method:

$scope.cart.push(item);

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

The issue of Elasticsearch results not being correctly parsed as JSON objects by JavaScript when retrieved from a Python client

I am facing an issue with extracting a Javascript object from the Elasticsearch(2.1.1) response received through my Python (2.7) client. Python code: es=Elasticsearch(); @app.route('/output') def findSpots(): lat = request.args.get('la ...

Error: The function styles$1.makeStyles is not defined

Currently, I am experimenting with rollup for bundling. However, when I run the code, I encounter the following problem: https://i.stack.imgur.com/8xLT3.png import { makeStyles } from '@material-ui/styles'; const styles = makeStyles({ subHead ...

Is there a way to update my website with a google map feature that allows mousewheel events for panning instead of zooming?

I am currently working on a unique project that involves creating a mashup with Google Maps (v3) to display real-time GPS data of Boston's buses. While Google typically uses scrolling for zooming in the maps, I believe using panning would be more prac ...

How can I retrieve text instead of HTML using jQuery.get?

I'm facing an issue where I am trying to retrieve data from another site using the code below: jQuery.ajaxSetup({ crossDomain: true, dataType: "jsonp text" }); jQuery.get(url, function(rawContent) { console.log(rawContent); }); However, ...

When nodemon is executed, it encounters an "Error: Cannot find module" issue, indicating that it may be searching in the incorrect directory

I recently encountered an issue with my Node.js project that utilizes nodemon. Despite having the package installed (located in /node_modules), I am experiencing an error when trying to start my Express server with nodemon through a script in my package.js ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...

Automatically scroll to the end of the data retrieved through ajax

I am currently developing a live chat website for my users and I am using ajax to fetch the chat messages. However, I am facing an issue where whenever I enter a new message, it does get added to the database and displayed, but the scroll doesn't auto ...

Node.js encountered an error: Attempting to access properties of an object that is undefined, specifically trying to read 'TokenType'

I've encountered an issue with my node.js application. It has a simple login page where 'user1' can access a private Power BI report. Everything seems to be working fine, except when 'user1' logs in, a blank page appears with the f ...

Likelihood of triggering a function based on percentage

Hey everyone, I'm looking to add some randomness to the buttons on my website. I have a Button that could activate function one, function two or function three. However, I want to make it so there is a 60% chance that function one gets called from the ...

What is the best way to utilize the JSON response received from a JQuery AJAX request?

Utilizing PHP and MySQL, I am swapping out content by sending an AJAX request to a PHP script that queries the database and returns a JSON object with the results. Although everything seems to be functional, I am struggling with a seemingly simple task - ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

What is the best way to encapsulate a function that uses `this.item.findElement()` from Selenium in a separate file?

I'm currently working on setting up a Selenium Webdriver and Cucumber.js test environment using Node.js. In the homePageSteps.js file, I have a check to verify if a banner exists on a page: Then('there should be a banner', async function() ...

Exploring the importance of defining a JSONP callback function

I am relatively new to JavaScript and struggling with an issue in my code. My code includes an Ajax request to a server, and I receive a response from it. Due to the cross-domain nature of the request, I am utilizing JSONP. $.ajax({ url: "***", c ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

Implement rotation in Three.js that mirrors the functionality of Blender

Is there a way to permanently change the default rotation of a mesh in three.js after it has been loaded? For example, if I load a mesh with a rotation of 0,0,0, can I then rotate it 90 degrees on the X axis and set this new rotation as 0,0,0? It's i ...

Issues encountered while working with dynamic content in fluentlenium

While conducting tests using fluentlenium on my application, I encountered some errors. I am utilizing Play Framework and Slickgrid to generate my grid. Slickgrid dynamically creates the grid in javascript. The structure of the grid that is generated looks ...

How can we enforce that the input consists of digits first, followed by a space, and then

Can regex (with javascript possibly) be used to mandate numbers, followed by a space, and then letters? I'm a bit lost on where to start with this... I understand that using an HTML5 pattern would work for this... [0-9]+[ ][a-zA-Z0-9]+ However, I ...

Updating and eliminating text within an array of objects using Vue JS

My Axios request pulls in an array of objects named 'uniquecolors'. Here is what it looks like: mycolors color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

Arranging an array of objects by their unique identifiers

Given an array of objects containing root and list elements in a tree structure, how can I efficiently organize them into a tree with an unknown depth? Each object has a parent element ID property. I am currently working on building a menu. While I have s ...