Search code examples
angularjsangularjs-service

AngularJs: Controllers calls service method


I tried to create a method in the services.js :

var esServices= angular.module('esServices', []);

esServices.factory('boxItems', ['$http', function($http) {
              ................
          }]); 

esServices.factory('cartItems', ['$cookieStore', function($cookieStore) {
        array = $cookieStore.get('key');
        var cartItems = new function(){},           
        cartItems.addItem = function(itemSelected){     
        $cookieStore.put('key', []);        
    array.push(itemSelected);
   $cookieStore.put('key', array);   
                }
      }]);

in my controllers I call the service method:

         esControllers.controller('esList', ['$scope','cartItems','$cookieStore',
                    function($scope,cartItems,$cookieStore) {          
              cartItems.addItem($scope.element,function(){});
     };
  }]);

(itemSelected is an object) 

Do you Know if it is possible to pass values (objects) from Controller to Service Method in this way?

Somebody can help me!!!


Solution

  • esServices.factory('cartItems', ['$cookieStore', function($cookieStore) {
            return {
                addItem: function(itemSelected){
                    var array = $cookieStore.get('key');       
                    array.push(itemSelected);
                    $cookieStore.put('key', array);
                },
                removeItem: function(){
                    //...
                }
            }    
    }]);
    

    then call using

    cartItems.addItem(itemSelected);