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

Having trouble setting the value in edit mode for Angular's ui-select2 component

<select id="e1" style="width:100%" ui-select2 tabindex="-1" ng-init="GetAllAgent()" ng-model="Agent" ng-options="ctr as ctr.AgentName for ctr in ListAgent track by ctr.AgentId" ng-change="GetSubAgentList(Agent.AgentId)"> <option value=""> < ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

Instructions for transforming DOM information into a JSON format

I have multiple inputs within my document, as shown in the code snippet below. My goal is to create a string or JSON object using the input names and values. var arr= []; $('ul li input').each(function(){ let name = $(this).attr(' ...

Having trouble deciphering the JSON data structure in JavaScript

How can values be passed back to a form that was submitted to the server using Ajax? In this view (shown below), a simple data structure is returned for testing purposes: def detail(request, widget_id): widget = get_object_or_404(Widget, pk=widget_i ...

I'm having trouble getting Grunt Source Maps to function properly within the foundation-press theme

I'm struggling to enable source maps for the npm package grunt-sass. Here's a snippet from my Gruntfile.js: The issue lies in this line: sourceMap: true, at line 13 module.exports = function(grunt) { var jsApp = [ 'js/app.js' ...

Discovering the magic of obtaining a random element in Vue.js

I have 3 captivating hero images along with their unique content, and I am looking to showcase them randomly to users each time they refresh the page! My challenge lies in efficiently loading these large hero images using jQuery. Currently, all three imag ...

Tips for moving a texture horizontally across a sphere using threejs

I have a 360 degree viewer tool. Is there a way to load a texture in a specific position that will rotate the original image by a certain number of degrees or units around the Y-axis without altering anything else about how the picture is displayed? If s ...

Here's a unique version: "Strategies for indicating a lack of matching records when utilizing the default filter in AngularJS UI

Is there a way to display a "No matched record found" message when using the default filter in AngularJS UI Grid? Currently, when applying a filter and no matching data is found, a blank screen is shown. ...

What is the best way to showcase a PDF in Django that is saved as a blob in a MySQL database?

Within my web application, users have the ability to upload a PDF file which is then stored directly in the MySQL database for security reasons. Utilizing the code snippet below, this process allows the uploaded file to be safely saved within the database ...

New techniques in VueJS 3: managing value changes without using watchers

I am currently working on coding a table with pagination components and I have implemented multiple v-models along with the use of watch on these variables to fetch data. Whenever the perPage value is updated, I need to reset the page value to 1. However, ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

What is the best way to consistently position a particular row at the bottom of the table in AG-grid?

I have successfully implemented a table using AG-grid. Here is the code snippet: .HTML <ag-grid-angular #agGrid style="width: 100%; height: 100%; font-size: 12px;" class="ag-theme-alpine" [rowData]=&quo ...

The synchronization between jQuery's onLoad and onDomready functions allows for seamless

When utilizing jsFiddle, I have noticed two options for initializing content using jQuery: onLoad or onDomReady. I have tested most of the scripts I've written and found no noticeable functional difference. Upon researching via Google, I discovered o ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

Delay the v-alert display after an item is added to the array basket using setTimeout

here is my custom rightTableMenu template <template> <div> <h1 align="center">{{ title }}</h1> <v-alert type="info" icon="mdi-emoticon-sad" v-if="basketStatus"> Empty Basket, please add some to basket < ...

Tips for utilizing identical properties across numerous styled elements:

Utilizing the styled-components library, I have enhanced the header components from the Blueprintjs library. The current template for the H6 component appears as follows: export const DH6 = styled(H6)` color: ${(props) => (props.white ? "white&qu ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Stunning slide-in and slide-out animation when transitioning between AngularJS states

When creating a single page application, I wanted to implement a slide-right effect for new pages and a slide-left effect for old pages when the user clicks on a button. To achieve this, I referred to a helpful resource () that demonstrated applying CSS cl ...