0

Creating a shopping cart app I'm trying to pass an object into a service function using Angular. I took the advice from another post but for some reason I'm still getting an unprovided error on page load, and a syntax error for some odd reason. The errors seem to stem from here:

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

The controller:

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

            // Recibir el producto por id pasado en el UI-router
            var prod = Productos.findById($stateParams.id);
            $scope.producto = prod;
            //ng-click addToCart desde el factory
            $scope.addToCart = Carrito.addToCart(prod);

}])

And the service it implements (Shortened):

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

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

Any help would be very much appreciated...

edit: Entire service here. Maybe there's something I'm fundamentally doing wrong?

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

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

    var unProducto = function() {

        this.Nombre = "";
        this.stockid = 0;
        this.Descripcion = "";
        this.Precio = 0;
        this.Familia = 1;
        this.Modificadores = [];
        this.Cantidad = 1;
        this.SKU = function () {return "" + this.stockid + 
        this.Modificadores.mod1 + this.Modificadores.mod2 + 
        this.Modificadores.mod3 + this.Modificadores.mod4 + 
        this.Modificadores.mod5};

    }


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

        };

        this.getProducto = 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 es un ng-model pasasdo por ng-click=addtoCart(producto) 
            en cualquier boton de compra. Hay que cargar los datos en el html */ 

            console.log("Passed: " + Prod + " -- into Carrito.addToCart...");
            unProducto.Nombre = Prod.Nombre;
            unProducto.stockid = Prod.stockid;
            unProducto.Descripcion = Prod.Descripcion;
            unProducto.Precio = Prod.Precio;
            unProducto.Familia = Prod.Familia;
            unProducto.Cantidad = parseInt(Prod.cantidad);
            unProducto.Modificadores = {
                "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].Cantidad++;
            } else {
                Carrito.carritoUsuario.push(unProducto);
                console.log("Added: " + unProducto + " -- to the Carrito...");
            }

        };

        this.totalCarrito = function() {
            var total = 0;
            _.forEach(carritoUsuario, function (e) {
                total += parseFloat(e.Precio) * parseFloat(e.Cantidad);
            });
            return total;
        }

}]);

Rewritten as a factory, still the same unprovided error:

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

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

    var unProducto = function() {

        this.Nombre = "";
        this.stockid = 0;
        this.Descripcion = "";
        this.Precio = 0;
        this.Familia = 1;
        this.Modificadores = [];
        this.Cantidad = 1;
        this.SKU = function () {return "" + this.stockid + 
        this.Modificadores.mod1 + this.Modificadores.mod2 + 
        this.Modificadores.mod3 + this.Modificadores.mod4 + 
        this.Modificadores.mod5};

    }


        /* For now this searches the local array */ 

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

        },

        getProducto : 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 es un ng-model pasasdo por ng-click=addtoCart(producto) 
            en cualquier boton de compra. Hay que cargar los datos en el html */ 

            console.log("Passed: " + Prod + " -- into Carrito.addToCart...");
            unProducto.Nombre = Prod.Nombre;
            unProducto.stockid = Prod.stockid;
            unProducto.Descripcion = Prod.Descripcion;
            unProducto.Precio = Prod.Precio;
            unProducto.Familia = Prod.Familia;
            unProducto.Cantidad = parseInt(Prod.cantidad);
            unProducto.Modificadores = {
                "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].Cantidad++;
            } else {
                Carrito.carritoUsuario.push(unProducto);
                console.log("Added: " + unProducto + " -- to the Carrito...");
            }

        },

        totalCarrito : function() {
            var total = 0;
            _.forEach(carritoUsuario, function (e) {
                total += parseFloat(e.Precio) * parseFloat(e.Cantidad);
            });
            return total;
        }
    };

}]);
mitbanip
  • 179
  • 3
  • 13
  • Can you post the error messages? – azium May 21 '15 at 17:44
  • This is a syntax error: `ng-submit="addToCart({{producto}})"` it should be `ng-submit="addToCart(producto)"` – azium May 21 '15 at 17:44
  • Also, you should post your entire service. I think the reason you're getting an error on page load is because you're service is not returning an object. – azium May 21 '15 at 17:47
  • I added the enitre service in the OP. Is there something I'm fundamentally doing wrong? – mitbanip May 21 '15 at 18:13
  • As for my error.. It's sure not helpful to me:Unknown provider: <-- It's as if I'm not injecting the service into the controller, though I am. – mitbanip May 21 '15 at 18:17
  • Hmm, well I think you should look at this https://github.com/toddmotto/angularjs-styleguide#services-and-factory for the difference between `service` and `factory`. They way you are writing your service you need to instantiate with `new ServiceName()`. I think you might be wanting to write a `factory` instead. – azium May 21 '15 at 18:20
  • [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=
    copeProvider%20%3C-%20%24scope%20%3C-%20Carrito I will instead try to make a factory out of this, though I already attempted it. I'm mostly using factories, but I'm not sure how to write the return for addToCart if I did make a factory. I'll read the article and try it.
    – mitbanip May 21 '15 at 18:30
  • try giving your anonymous function a name. `function Carrito (args) {}` – azium May 21 '15 at 18:32
  • You can return functions in factories like so: `function service () { return { addToCart: function (args) { ... } } }` – azium May 21 '15 at 18:34
  • I rewrote is as a factory in the OP, but it still gives the same unprovided error. I think this is much simpler than something wrong with the service. But I assure you all dependencies I can see are properly injected. – mitbanip May 21 '15 at 18:36

1 Answers1

0

You don't need to pass "producto" in double curly brackets, since it is inside a directive (ng-submit). So...

ng-submit="addToCart(producto)"

A relevant topic explains why here: AngularJS: ng-show / ng-hide

Community
  • 1
  • 1