I am currently using Angular to develop a shopping list application. To facilitate testing, I have set up two pre-made lists with two and three pre-defined items each. However, the goal is for users to dynamically add both items and lists themselves in the future. I have successfully implemented an "Add Item" button that allows users to append new items to each list.
Feel free to experiment with the functionality by accessing this CodePen - http://codepen.io/anon/pen/WraZEv
<body ng-controller="notepadController as notepad">
<header ng-repeat="list in notepad.lists">
<div>Delete list</div>
<h1>{{list.name}}</h1>
</header>
<div ng-repeat="list in notepad.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
<ul>
<li ng-repeat="item in list.items">
<label>
<input type="checkbox" ng-model="item.checked">
{{item.name}}
</label>
<form name="removeItemForm" ng-submit="itemCtrl.removeItem(list)">
<input type="submit" value="Remove Item">
</form>
</li>
</ul>
<form name="itemForm" ng-submit="itemCtrl.addItem(list)">
<input type="text" ng-model="itemCtrl.item.name">
<input type="submit" value="Add Item">
</form>
</div>
</body>
Below is the Javascript code:
(function(){
var app = angular.module('notepadApp', []);
var shoppingLists = [
{
name: 'groceries',
items: [
{
name: 'milk',
checked: false
},
{
name: 'eggs',
checked: false
}
]
},
{
name: 'cvs',
items: [
{
name: 'pills',
checked: false
},
{
name: 'cotton balls',
checked: false
},
{
name: 'cigs',
checked: false
}
]
}
];
app.controller('notepadController', function(){
this.lists = shoppingLists;
});
app.controller('ItemController', function(){
this.item = {};
// add new item to a shopping list
this.addItem = function(list){
list.items.push(this.item);
this.item = {};
};
// remove an item from a shopping list
this.removeItem = function(list){
var listOfItems = [];
var i;
for (i = 0; i < list.items.length; i++){
list.items.splice(list.items[i,1]);
}
};
});
})();
Please note that clicking on the Remove Item button currently clears all items from a list instead of targeting and deleting only the specific item intended. While I understand the cause of this issue, I am struggling to identify how to pinpoint the index of the item to be removed so that the Remove Item button functions correctly.