AngularJs:控制器调用服务方法

时间:2014-01-08 09:52:54

标签: angularjs angularjs-service

我尝试在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);   
                }
      }]);

在我的控制器中我调用服务方法:

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

(itemSelected is an object) 

您是否知道是否可以通过这种方式将值(对象)从Controller传递到Service Method?

有人可以帮助我!!!

2 个答案:

答案 0 :(得分:3)

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

然后使用

进行呼叫
cartItems.addItem(itemSelected);

答案 1 :(得分:2)

您应该在控制器中注入服务,如

        var app = angular.module('app', ['ngCookies'] );
        app.factory('cartItems', ['$cookieStore', function($cookieStore) {
          return {
             addItems : function(){
                alert('hello');   
             }  
          }
       }]);
       app.controller('MyController',function($scope,cartItems){
         $scope.test = 'my test';
         cartItems.addItems();
      });

如果您想使用丑陋的语法:)只需从工厂返回 cartItems

相关问题