通过角度.js中的公共服务在2个控制器下共享数据

时间:2017-02-03 13:42:05

标签: javascript angularjs

Sub aaa()
    Set Rky = CreateObject("VBScript.RegExp")
    Rky.Pattern = "\w*([0-9])" & "mm"
    For i = 1 To Range("A65536").End(3).Row
      If Cells(i, "a").Value Like "*mm*" Then
        Cells(i, "C") = Rky.Execute(Cells(i, "A")).Item(0)
      End If
    Next i
End Sub

HTML代码:

(function () {
'use strict';

angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service("ShoppingListCheckOffService", ShoppingListCheckOffService);

ToBuyController.$inject = ["ShoppingListCheckOffService"];

function ToBuyController(ShoppingListCheckOffService) {

  var buyItem = this;

  buyItem.items = ShoppingListCheckOffService.getItems();
  buyItem.removeItem = function (itemIndex) {
  ShoppingListCheckOffService.removeItem(itemIndex);
  }
}

AlreadyBoughtController.$inject = ["ShoppingListCheckOffService"];
function AlreadyBoughtController(ShoppingListCheckOffService){
    var boughtItem = this;

    boughtItem.itemName = "";
    boughtItem.itemQuantity = "";
    // console.log(boughtItem.name);


    boughtItem.items = function () {
      ShoppingListCheckOffService.addItem(boughtItem.itemName, boughtItem.itemQuantity);
    }

  //  boughtItem.items = ShoppingListCheckOffService.getItems();

  }


function ShoppingListCheckOffService() {
  var service = this;

  // List of shopping items
  var items = [{
    name: "Donuts",
    quantity: "200"
  },
  {
    name: "Cookies",
    quantity: "10"
  },
  {
    name: "Cake",
    quantity: "1"
  },
  {
    name: "Bread",
    quantity: "2"
  },
  {
    name: "Candies",
    quantity: "30"
  }
];

  service.addItem = function (itemName, itemQuantity) {
    var newItems = [];
    var item = {
      name: itemName,
      quantity: itemQuantity
    };
    newItems.push(item);
    return newItems;
  };

  service.removeItem = function (itemIndex) {
    items.splice(itemIndex, 1);

  };

  service.getItems = function () {
    return items;
  };
}

})();

如何编码以便点击" Bought"从一个列表中删除并在另一个Div上显示。在同一服务下使用两个不同的控制器在控制器" AlreadyBoughtController" addItem()无法正常工作

1 个答案:

答案 0 :(得分:0)

您正在addItem方法中创建空白数组并在其中添加项目。所以你需要改变你的addItem方法,如as-

service.addItem = function (itemName, itemQuantity) {    
    var item = {
      name: itemName,
      quantity: itemQuantity
    };
    items.push(item);
    return items ;
  };