当我试图在" 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>
(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;
};
}
})();
答案 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。它工作正常,看看