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

标签 javascript angularjs

我正在尝试创建一个充当购物篮的服务,允许用户添加/删除项目。但是,我遇到以下错误消息无法读取未定义的属性“addServiceItem”。这是到目前为止我的代码:

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;
    }

}

最佳答案

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

The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service.

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);

关于javascript - 创建允许用户添加或删除项目的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37576087/

相关文章:

javascript - 如果文本中存在大写字母或数字,则测试返回 false

javascript - document.write 在已加载并关闭的网站上

javascript - 获取数组中出现次数最多的项

JavaScript 遍历 NodeList

node.js - 在 Windows 上使用 karma-browserify 时出现“找不到模块”错误

javascript - Django 模板破坏 DataTable

javascript - 无法使用 Angular js 中的选项卡从日期选择器中获取选定的日期

html - flex 布局(使用 Angular Material )在某些平台上中断

angularjs - Ui-sref 未在 ionic 框架中生成正确的 url

javascript - 使用 Controller As Syntax 和 ngRoute 分别加载 Controller