创建允许用户添加或删除项目的服务

时间:2016-06-01 18:20:55

标签: javascript angularjs

我正在尝试创建一个充当购物篮的服务,允许用户添加/删除项目。但是,我遇到以下错误消息Cannot read property 'addServiceItem' of undefined。到目前为止,这是我的代码:

controller.js

$scope.addServiceItem = function(bookingSelected, title, price, length) {
  if (bookingSelected === true) {
    BusinessService.manageServiceItems.addServiceItemcont(title, price, length);
  }
}

services.js

function BusinessService($http) {

  function manageServiceItems() {

    var serviceItem = [];

    function addServiceItem(title, price, length) {
      serviceItem.push({
        title: title,
        price: price,
        length: length
      });
    }

    this.getServiceItem = function() {
      return serviceItem;
    }

}

1 个答案:

答案 0 :(得分:3)

服务定义应该返回一个对象或函数。来自docs

  

服务工厂函数生成单个对象或函数   表示对应用程序其余部分的服务。物体   或者服务返回的函数被注入到任何组件中   (控制器,服务,过滤器或指令)指定依赖项   在服务上。

function BusinessService($http) {
  var BusinessService = this, serviceItem = [];

  BusinessService.manageServiceItems = {
      addServiceItem: function(title, price, length) {
       serviceItem.push({
        title: title,
        price: price,
        length: length
       });
     },
     getServiceItem: function() {
      return serviceItem;
    }
  }
  return BusinessService;
};

var myModule = angular.module('myModule', [])
.factory('BusinessService', BusinessService);