(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;
};
}
})();
HTML Code:
<!-- To Buy List -->
<div class="col-md-6" ng-controller='ToBuyController as buyItem'>
<h2>To Buy:</h2>
<ul>
<li ng-repeat="item in buyItem.items">
Buy {{item.quantity }} of {{ item.name }}
<button ng-click="buyItem.removeItem($index)" class="btn btn-default"><span class="glyphicon glyphicon-ok">Bought</button>
</li>
</ul>
<div class="emptyMessage">Everything is bought!</div>
</div>
<!-- Already Bought List -->
<div class="col-md-6" ng-controller='AlreadyBoughtController as boughtItem'>
<h2>Already Bought:</h2>
<ul>
<li ng-repeat="item in boughtItem.items">
Bought {{ item.quantity }} of {{ item.name }}
</li>
</ul>
<div class="emptyMessage">Nothing bought yet.</div>
</div>
Modify the code so that clicking on "Bought" removes an item from one list and adds it to another. Two different controllers are used under the same Service. The addItem() method under the controller "AlreadyBoughtController" needs debugging.