Reputation: 315
Angular Newb, trying to make a simple checklist app and understand relationships. The user can add a list of items. My ItemList class has a title, date and a collection of items. My Item class has item names and quantities. How can I use input boxes with ng-model multiple times?
Here's my ItemList.cs
namespace BringIt.Models {
public class ItemList {
public int Id { get; set; }
public string Title { get; set; }
public DateTime EventDate { get; set; }
public ICollection<Item> Items { get; set; }
}
}
and Item.cs
namespace BringIt.Models {
public class Item {
public int Id { get; set; }
public string ItemName { get; set; }
public int ItemQty { get; set; }
public string Person { get; set; }
public ItemList ItemList { get; set; }
}
}
and my basic form
<form ng-submit="controller.save()">
Title <input ng-model="controller.itemList.title" />
Item Name <input ng-model="controller.item.itemName"/>
Quantity <input ng-model="controller.item.itemQty" />.
//would like to do it again for more items
Item Name 2 <input ng-model="controller.item.itemName" />
Quantity 2 <input ng-model="controller.item.itemQty" />
<button type="submit">Submit</button>
</form>
When I run the code and type something into the first model, it instantly shows in the second matching input box. I ultimately want to allow the user to add as many items as they would like, and the collection would just keep increasing. Also, any other suggestions for best practices I may be missing are always helpful.
I've now got the following code, which almost works, but doesn't add new spaces for more objects after I fill in the first one.
public addNew() {
debugger;
this.items = []
var item = {itemName: "default name", itemQty: "default qty"}; // you can set default values here
this.items.push(item);
}
Upvotes: 0
Views: 77
Reputation: 26940
You can iterate with ng-repeat
:
<div ng-repeat="item in items">
Item Name {{$index}} <input ng-model="item.itemName" />
Quantity {{$index}} <input ng-model="item.itemQty" />
</div>
<button ng-click="addNew()"></button>
Add new item:
$scope.items = [{
itemName: 'existing item name',
itemQty: 'existing item quantity'
}];
$scope.addNew = function () {
var item = {}; // you can set default values here
items.push(item);
};
Upvotes: 3