【发布时间】:2017-06-09 16:45:38
【问题描述】:
我使用 angularJS,并且我的页面上有一个表格,我制作了一个按钮来添加带有输入字段的行。我的解决方案适用于在表单中添加行和输入字段的值,但在我需要删除特定行的情况下效果不佳。我将一个函数用于表单,另一个用于添加和删除行。
是这样的:
<div ng-init="tmplCtr.newPeople()">
<div class="col-lg-12">
<input name="postsubmit" class="btn btn-default btn-sm" type="submit" value="Save table" ng-click="tmplCtr.newTable(tmplCtr.table)" />
<button class="btn btn-default btn-sm" ng-click="tmplCtr.editRow()">Add row</button>
</div>
<form name="peopleForm" novalidate>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="place-name">Name</th>
<th class="place-value">Lastname</th>
<th class="place-options">Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="people in tmplCtr.peoples">
<td class="place-name"><input type="text" name="" class="form-control" autocomplete="off" ng-model="tmplCtr.peoples.values[$index].name"></td>
<td class="place-last"><input type="text" name="" class="form-control" autocomplete="off" ng-model="tmplCtr.peoples.values[$index].lastname"></td>
<td class="place-options"><button class="btn btn-danger btn-md btn-delete" ng-click="tmplCtr.editRow($index)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</form>
当我按下按钮添加行时,我得到了行,但是当我按下删除行时,我从屏幕中删除了行,但在数组中删除了最后一行,而不是按索引。除此之外,该行的值也不会从表单范围中删除。功能是:
function editRow(item) {
if(item == undefined) {
vm.peoples.push({});
} else {
vm.peoples.splice(item,1);
}
}
谁能帮帮我?
【问题讨论】:
-
您不应该使用 ng-model="tmplCtr.table.values[$index].name" 而是使用 ng-model="place.name" 并且与其他字段类似 在删除按钮上单击,您可以发送地点对象。 ng-click="tmplCtr.editRow(place)" 在 editRow 里面你可以在数组中查找位置并删除它
-
但是添加没关系,我需要从 tmplCtr.peoples.values 数组中删除对象。我在函数编辑行中发送了好的索引,但是 vm.peoples.splice(item,1);不知何故做得不好
-
你能不能做一个plunker?
-
我现在不能,等我做的时候我会在这里更新
-
您实际上是在
tmplCtr.peoples中进行迭代,但您在tmplCtr.peoples.values中应用了$index?不能说这对你有什么意义。
标签: javascript angularjs arrays forms