[英]How to add objects to a key within another dynamically created object in Angular?
我正在使用Angular創建列表應用。 出於測試目的,我有兩個預先創建的列表,每個列表都包含預先創建的名稱和項目。 最終,最初將向用戶顯示一個空白列表,用戶可以在其中添加項目。 然后他們可以為新項目添加新列表。 到目前為止,我可以在現有列表中添加和刪除項目,也可以添加新列表。 但是我無法將新項目添加到新創建的列表中。 對於行list.items.push(this.item);
出現“無法讀取未定義的屬性'push'”錯誤list.items.push(this.item);
。 我的猜測是,當我創建一個新列表時,沒有添加items
,這就是為什么它是未定義的。 創建新列表時,我嘗試創建items
鍵,但無法正常工作。 無論如何這可能不是問題。
https://codepen.io/anon/pen/oWRQvQ
這是標記:
<div ng-app="notepadApp">
<div ng-controller="notepadController as notepadCtrl">
<header ng-repeat="list in notepadCtrl.lists">
<div>Delete list</div>
<h1>{{list.name}}</h1>
</header>
<div ng-repeat="list in notepadCtrl.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="itemForm" ng-submit="itemCtrl.removeItem(list, $index)">
<input type="submit" value="remove">
</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>
<form name="addListForm" ng-submit="notepadCtrl.addList(lists)">
<input type="text" ng-model="notepadCtrl.list.name">
<input type="submit" value="Add list">
</form>
</div>
</div>
該腳本是:
(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: 'razors',
checked: false
}
]
}
];
app.controller('notepadController', function(){
this.lists = shoppingLists;
this.list = {};
this.addList = function() {
this.lists.push(this.list);
this.list = {};
};
});
app.controller('ItemController', function(){
this.item = {};
this.addItem = function(list){
list.items.push(this.item);
this.item = {};
};
this.removeItem = function(list, index) {
list.items.splice(index, 1);
};
});
})();
您在兩個地方創建一個新列表; 一次在控制器初始化時,再次在addList
函數中。
在這兩個地方,都需要一個items
數組來匹配另一個列表使用的結構。 在創建新列表的兩個地方,都將初始化代碼更改為this.list={items:[]};
為了確保有要推送的items []
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.