如何在listjs中传递列表的值作为函数的参数

时间:2017-02-03 18:43:24

标签: angularjs

HTML代码

当我试图在" itemBought List"中显示值时,在第二个控制器中点击按钮,它的名称和数量呈现空字符串,而我在itemToBuy.itemList"中有相同的数据。

似乎名称和数量的数据不会传递到addItemToBoughtList()函数中。如何实现这一点。

    <!-- To Buy List -->
<div class="col-md-6" ng-controller="ToBuyController as itemToBuy">
<h2>To Buy:</h2>
<ul>

<li ng-repeat="item in itemToBuy.itemList"> Buy {{item.itemQuantity}} of {{item.itemName}}
<button class="btn btn-default" ng-click="itemToBuy.addItemToBoughtList()"><span class="glyphicon glyphicon-ok"></span> Bought</button></li>

</ul>
<div class="emptyMessage">Everything is bought!</div>
</div>

<!-- Already Bought List -->
<div class="col-md-6" ng-controller="AlreadyBoughtController as itemBought">
<h2>Already Bought:</h2>
<ul>
<li ng-repeat="item in itemBought.items">
Bought {{ items.quantity }} of {{ item.name }}</li>
</ul>
<div class="emptyMessage">Nothing bought yet.</div>
</div>
</div>

Javascript代码

    (function (){
'use strict';

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

ToBuyController.$inject = ['ShoppingListCheckOffService'];
function ToBuyController(ShoppingListCheckOffService) {
var itemToBuy= this;

itemToBuy.itemName = "";
itemToBuy.itemQuantity = "";

itemToBuy.itemList = [
{itemName : 'cookies', itemQuantity : 10},
{itemName : 'napkins', itemQuantity : 15}
];

itemToBuy.addItemToBoughtList = function () {
ShoppingListCheckOffService.addItemToBoughtList(itemToBuy.itemName, itemToBuy.itemQuantity);
}
}


AlreadyBoughtController.$inject = ['ShoppingListCheckOffService'];
function AlreadyBoughtController(ShoppingListCheckOffService) {
var itemBought = this;
itemBought.name="";
itemBought.items = ShoppingListCheckOffService.getItems();
}

function ShoppingListCheckOffService() {
var service = this;

// List of shopping items
var items = [];

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

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

})();

1 个答案:

答案 0 :(得分:1)

将项目传递给addItemToBoughtList函数

<ul>

 <li ng-repeat="item in itemToBuy.itemList"> Buy {{item.itemQuantity}} of {{item.itemName}}
 <button class="btn btn-default" ng-click="itemToBuy.addItemToBoughtList(item)"><span class="glyphicon glyphicon-ok"></span> Bought</button></li>

</ul>

并在js

中的函数中接收它
itemToBuy.addItemToBoughtList = function (item) {
ShoppingListCheckOffService.addItemToBoughtList(item.itemName, item.itemQuantity);
}

我已使用您的代码创建了plunker。它工作正常,看看