Populate a shopping cart with items using AngularJS

Greetings from an Angular newbie! I'm currently working on developing a shopping cart specifically designed for college students. The objective is to input the name and price of items into a text field and upon clicking a button, have the item added to a list. Unfortunately, every time I click the button, nothing seems to happen. I've checked the console for errors but found none. Here's a snippet of my code:

<!DOCTYPE html>
<html ng-app = "myApp">
<head>
    <title>Shopping Cart</title>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">     </script>
    <script src = "app.js"></script>        
</head>
<body ng-controller = "myShoppingCart">

            <h1>Add to cart</h1>
            <form >
                    <p>Product: <input type = "text" ng-model = "nameProduct"></p>
                    <p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
                    <input type = "submit" value = "Add" ng-click = "addProduct()">
            </form>

        </div>

        <div">
            <ul>
                <li ng-repeat = "product in products">
                    <span>{{product.name}}</span>
                    <span>{{product.price}}</span>
                    <span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
                    <span>{{product.price*amount}}</span>
                </li>
            </ul>
        </div>
  </body>
</html>

Here's a peek at my JavaScript code:

var myApp = angular.module("myApp", []);

myApp.controller('myShoppingCart', function($scope) {

 $scope.products = [];

 function addProduct() {

    $scope.productos.push({nombre:$scope.nameProduct, price:$scope.priceProduct});
    $scope.nameProduct = "";
    $scope.priceProduct = "";
 }

});

Answer №1

You have incorrectly assigned the values to the wrong object. Additionally, there are several changes that need to be made. Make sure your button click function is properly written.

 $scope.addProduct= function () {
//code
}

Please replace your existing code with the following:

HTML

<!DOCTYPE html>
<html ng-app = "myApp">
<head>
    <title>Shopping Cart</title>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src = "app.js"></script>        
</head>
<body ng-controller = "myShoppingCart">

            <h1>Add to cart</h1>
            <form >
                    <p>Product: <input type = "text" ng-model = "nameProduct"></p>
                    <p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
                    <input type = "submit" value = "Add" ng-click = "addProduct()">
            </form>

        </div>

        <div>
            <ul>
                <li ng-repeat = "product in products">
                    <span>{{product.name}}</span>
                    <span>{{product.price}}</span>
                    <span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
                    <span>{{product.price*amount}}</span>
                </li>
            </ul>
        </div>
  </body>
</html>

and JavaScript Code

var myApp = angular.module("myApp", []);

myApp.controller('myShoppingCart', function($scope) {

 $scope.products = [];

$scope.addProduct= function () {

    $scope.products.push({name:$scope.name, price:$scope.priceProduct});
    $scope.nameProduct = "";
    $scope.priceProduct = "";
 }

});

Answer №2

<input type = "button" value = "Add" ng-click = "addProduct()">

It is necessary to

<input type = "button" value = "Add" ng-click = "addProduct()">

The submit button will send the form information to the server, which may not be what you want.

There are also some errors here:

<div">

And in this line (productos should be products):

$scope.products

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

Using React.js to compute dates based on user-inputted dates

Today was dedicated to tackling the coding challenge of creating a function. I'm currently working on a react app using the PERN stack. The form I'm working on includes multiple date inputs, with two date columns and a total days column. My goal ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Create a query string using JavaScript and combine multiple parameters into a single param

I am facing a challenge where I need to construct a query string in JavaScript and nest various parameters within one of the parameters. In PHP, I can achieve this using the http_build_query function. However, when attempting to do the same in JavaScript, ...

Ensuring the node array is easily accessible within the view

I am currently working on building a simple messaging system using express/nodejs. Although I have successfully implemented the feature to send messages to all users, I now want to enable users to have private 1-to-1 conversations. My aim is straightforwa ...

How can I display actual images received as escaped string literals from ExpressJS?

Is there a way to transform this data from ExpressJS into an actual image? The information I'm receiving looks like this instead of an image: {`data: 'PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\ ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

Toggle the visibility of the search Div using Angular UI

When using angular UI buttons, users can select search criteria by choosing between Patient, ID, or Date. If Patient or ID is selected, the searchByText div will be shown. If Date is selected, the searchByText will be hidden and the SearchBydateRange wil ...

What is the method for displaying console.log() messages on Heroku?

Lately, I've been making efforts to troubleshoot my app using console.log() within Node.js. Despite adding numerous lines of code for debugging purposes, I have yet to find them in the heroku log no matter how many times I check. $ heroku logs -n 20 ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: https://i.sstatic.net/yzovV.png After logging in, you will be directed to this page: https://i.sstatic.net/pZFou.png Now, I want the login page to have no navigation and look like this: https://i.sstatic.net/1sH9v ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

React table row render error

I am facing an issue with my React code: var PostRow = React.createClass({ render: function(){ var loading = <tr><td>one row</td></tr>; return( {loading} ) } }); An error message is bein ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

The method for organizing boxes on the stack exchange website's list page

I can't help but wonder about a unique and innovative feature on this stackexchange page that showcases all the stackexchange sites in a grid layout. Upon clicking on a site box, it expands in size while the surrounding boxes adjust their positions t ...

Alignment issue with Bootstrap 4 form fields within inline form group

My experience with Bootstrap 4 on certain pages has been quite challenging, specifically when it comes to aligning fields with labels to the left and maintaining an aligned appearance for input fields. Here is the snippet of my code: <div class="wrap ...

Converting a JSON Model object to HttpServletRequest in a legacy app using Angular JS and Spring REST

I am faced with the task of working on a large enterprise legacy Java application that relies heavily on servlets and JSPs. My plan is to modernize this outdated app by converting it into a Single Page application using Angular JS and Spring MVC REST. As ...