我正在尝试将文本框中的项目添加到列表中,并希望显示在主页上。这是我的代码示例
HTML代码:
<div ng-controller="purchaseInvoiceInquiryController as c" ng-init="c.initializeController()">
<input type="text" ng-model="c.name" placeholder="Enter the Book" />
<input type="text" ng-model="c.price" placeholder="Enter a Price" />
<button ng-click="c.addBooks()">Add the Book</button></p>
<td ng-repeat="x in c.books"> {{ x.name + ' - ' + x.price}}</td>
角度控制器代码为:
this.addBooks = function () {
c.books = [{
name: c.name,
price: c.price
}];
};
当我尝试添加另一个项目时,它仅在该列表中添加一个项目,它将覆盖值。
最佳答案
在控制器中将书籍初始化为空数组,然后使用数组的push方法添加新书籍。您可能需要添加逻辑以避免重复。
this.books = [];
this.addBooks = function () {
this.books.push({
name: c.name,
price: c.price
});
};