到目前爲止,我已經成功地創建了一個從ng-repeat中刪除元素並切換窗體的函數。我無法弄清楚如何編輯ng-repeat中的給定元素。編輯ng-repeat中的一個項目
理想情況下,我想單擊元素,並使表單顯示輸入中已有的值。因此,所有用戶需要做的是編輯所需的字段,單擊提交,然後將新更新的項目添加回原來的陣列。
這是我想出來的:
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
<input type="text" />
<input type="text" />
<button ng-click="vm.update()">Submit</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list">
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm()">E</span>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
和:
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function() {
vm.showEditForm = !vm.showEditForm;
};
vm.update = function() {
// ???
}
}
function testSrvc() {
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function() {
this.list.splice() //???
}
}
因此,使用你的建議,我是能夠針對在vm.toggleEditForm($指數)的使用項目$指數。它將控制器上的索引保存到一個變量中,然後我可以在編輯功能中使用該變量。 如何使用現有值預填充輸入字段? – odran037
只需使用我在我的回答中提出的建議。不要使用$索引。傳遞對象來編輯它自己。複製它,將其存儲在範圍變量中,使用ng-model將您的字段綁定到此項目副本。正如我在答案中所解釋的那樣。 –