Transferring information submitted in a form to a service using AngularJS

Trying to implement a shopping cart app where I need to pass an object into a service function using Angular. Following advice from another post, but encountering an unprovided error and a strange syntax error on page load. The issues seem to be originating here:

<form class="cart nobottommargin clearfix" ng-submit="addToCart({{producto}})" novalidate >

Here is the controller code:

.controller('DetalleProductoController',
    ['$scope', '$stateParams', 'Productos', 'Carrito',
        function ($scope, $stateParams, Productos, Carrito) { 

            // Fetching the product by id passed in the UI-router
            var prod = Productos.findById($stateParams.id);
            $scope.producto = prod;
            //ng-click addToCart from the factory
            $scope.addToCart = Carrito.addToCart(prod);

}])

Below is the ssummary of the service being implemented:

MyApp.service('Carrito', ['Productos', '$scope', '$http', 
    function (Productos, $scope, $http){

    var carritoUsuario = [];
    var todosLosProductos = Productos.todos();
    this.addToCart = function(Prod) {};

Any assistance would be greatly appreciated...

edit: Here's the full service code. Is there something fundamentally wrong that I'm doing?

MyApp.service('Carrito', ['Productos', '$scope', '$http', 
    function (Productos, $scope, $http){

    var carritoUsuario = [];
    var todosLosProductos = Productos.todos();

    var unProducto = function() {

        this.Name = "";
        this.stockid = 0;
        this.Description = "";
        this.Price = 0;
        this.Family = 1;
        this.Modifiers = [];
        this.Quantity = 1;
        this.SKU = function () {return "" + this.stockid + 
        this.Modifiers.mod1 + this.Modifiers.mod2 + 
        this.Modifiers.mod3 + this.Modifiers.mod4 + 
        this.Modifiers.mod5};

    }


        /* Currently, this searches the local array */ 
        this.findBySKU = function(sku) {
            console.log("Finding: " + sku + " from Carrito service findBySKU...");
            _.find(carritoUsuario, function (product){
                return product.stockid == sku; 
            });

        };

        this.getProduct = function(id) {
            console.log("Getting: " + id + " from Carrito service getProducto...");
            Producto.findById(id);
        };

        this.getCart = function() {
            console.log("Getting cart from Carrito service getCart");
            carritoUsuario;
        };

        this.addToCart = function(Prod) {
            /* Prod is an ng-model passed via ng-click=addtoCart(product) 
            on any purchase button. Data needs to be loaded into the html */ 

            console.log("Passed: " + Prod + " -- into Carrito.addToCart...");
            unProducto.Name = Prod.Name;
            unProducto.stockid = Prod.stockid;
            unProducto.Description = Prod.Description;
            unProducto.Price = Prod.Price;
            unProducto.Family = Prod.Family;
            unProducto.Quantity = parseInt(Prod.quantity);
            unProducto.Modifiers = {
                "mod1":Prod.mod1,
                "mod2":Prod.mod2,
                "mod3":Prod.mod3,
                "mod4":Prod.mod4,
                "mod5":Prod.mod5
               };
            unProducto.SKU = "" + Prod.stockid + Prod.mod1 + Prod.mod2 + Prod.mod3 + Prod.mod4 + Prod.mod5;

            if(angular.isDefined(Carrito.findBySKU(unProducto.SKU))) {
                var i = _.findIndex(this.carritoUsuario, unProducto.SKU);
                Carrito.carritoUsuario[i].Quantity++;
            } else {
                Carrito.carritoUsuario.push(unProducto);
                console.log("Added: " + unProducto + " -- to the Carrito...");
            }

        };

        this.totalCart = function() {
            var total = 0;
            _.forEach(carritoUsuario, function (e) {
                total += parseFloat(e.Price) * parseFloat(e.Quantity);
            });
            return total;
        }

}]);

Attempted reimplementation as a factory, yet still facing the same unprovided error:

MyApp.factory('Carrito', ['Productos', '$scope', '$http', 
    function (Productos, $scope, $http){

    var carritoUsuario = [];
    var todosLosProductos = Productos.todos();

    var unProducto = function() {

        this.Name = "";
        this.stockid = 0;
        this.Description = "";
        this.Price = 0;
        this.Family = 1;
        this.Modifiers = [];
        this.Quantity = 1;
        this.SKU = function () {return "" + this.stockid + 
        this.Modifiers.mod1 + this.Modifiers.mod2 + 
        this.Modifiers.mod3 + this.Modifiers.mod4 + 
        this.Modifiers.mod5};

    }


        /* Currently, it searches the local array */ 

        return {
        findBySKU : function(sku) {
            console.log("Finding: " + sku + " from Carrito service findBySKU...");
            return _.find(carritoUsuario, function (product){
                return product.stockid == sku; 
            });

        },

        getProduct : function(id) {
            console.log("Getting: " + id + " from Carrito service getProducto...");
            return Producto.findById(id);
        },

        getCart : function() {
            console.log("Getting cart from Carrito service getCart");
            return carritoUsuario;
        },

        addToCart : function(Prod) {
            /* Prod is an ng-model passed via ng-click=addtoCart(product) 
            on any purchase button. Data needs to be loaded into the html */ 

            console.log("Passed: " + Prod + " -- into Carrito.addToCart...");
            unProducto.Name = Prod.Name;
            unProducto.stockid = Prod.stockid;
            unProducto.Description = Prod.Description;
            unProducto.Price = Prod.Price;
            unProducto.Family = Prod.Family;
            unProducto.Quantity = parseInt(Prod.quantity);
            unProducto.Modifiers = {
                "mod1":Prod.mod1,
                "mod2":Prod.mod2,
                "mod3":Prod.mod3,
                "mod4":Prod.mod4,
                "mod5":Prod.mod5
               };
            unProducto.SKU = "" + Prod.stockid + Prod.mod1 + Prod.mod2 + Prod.mod3 + Prod.mod4 + Prod.mod5;

            if(angular.isDefined(Carrito.findBySKU(unProducto.SKU))) {
                var i = _.findIndex(this.carritoUsuario, unProducto.SKU);
                Carrito.carritoUsuario[i].Quantity++;
            } else {
                Carrito.carritoUsuario.push(unProducto);
                console.log("Added: " + unProducto + " -- to the Carrito...");
            }

        },

        totalCart : function() {
            var total = 0;
            _.forEach(carritoUsuario, function (e) {
                total += parseFloat(e.Price) * parseFloat(e.Quantity);
            });
            return total;
        }
    };

}]);

Answer №1

There is no need to include "producto" within double curly brackets when using it inside a directive like ng-submit. Simply use...

ng-submit="addToCart(producto)"

You can learn more about this concept from the following resource: AngularJS: ng-show / ng-hide

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

Navigating through Routing Express and sending data to a template

If I have the following code in my router.get() function, how can I output a template with the data without being able to use res.render()? router.get('/read', function(request, response) { res.send({"result": "Success sent from routes/index ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Locating the top 3 largest values in an HTML data table and highlighting them in red

Issue Description: I am working with data that displays the electricity consumption of different buildings in HTML tables. There is a possibility that these tables may contain duplicate values. With the use of jQuery, I am seeking a method to identify an ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Having trouble with ui-sref functionality within a Bootstrap dropdown menu

In the header.html file, I have the following angular code: <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> &l ...

Retrieving user email with Vue.js from Firebase

Currently, I am in the process of developing a chat application using Vue.js and Firebase. This project has been quite challenging for me as I am new to both Vue and Firebase. One specific issue I have encountered is trying to retrieve the user's ema ...

The Runtime Error encountered in NEXTJS: TypeError - Unable to iterate over 'games' as it is not

Attempting to create my inaugural website that showcases data from an API sans a tutorial. Does it seem like I may have overlooked something? I've successfully fetched the API and confirmed in the console log that the necessary data is present. Howev ...

A TypeError was not captured when attempting to access information about Ionic1 through the angular.module

For the past 48 hours, I've been struggling with an issue that's really getting on my nerves. If anyone knows how to fix this, it would be greatly appreciated: I'm working on an Ionic 1 project and need to make some updates, but nothing I t ...

Utilize React to dynamically load diverse data arrays into a slick slider component

I am currently working on a component that includes a slider displaying photos linked to different rooms. The next step is to move this slider to a separate page or component, which will display content for rooms, news, and promotions using different arr ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Tips for optimizing node_module file size

Currently, I'm developing 2-3 react applications and noticed that every time I run npm install, it ends up downloading numerous dependencies into the cumbersome "node-modules" folder, totaling around 250-300mb in size! This large size makes it challen ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...

Obtaining service data results in Angular: A step-by-step guide

To retrieve data from an API, I implemented a controller and service. The service code looks like this: var categories = []; var categoriesjon = function () { $http.get('http://localhost:18737/Category/GetCategories'). success(funct ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

Error: missing semicolon prior to the statement

I am looking to create a Java web application that includes a JSP page. However, when I load the page, I encounter the following error: SyntaxError: missing ; before statement The code for my JSP page is as follows: <%@ page language="java" contentTy ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...