[英]How to add a row on click of a “Add” button in angularJS
我想在单击“添加”按钮时在表格中添加一行。我正在尝试使用“ng-show”指令完成此操作,但即使没有单击“添加”按钮,该行也会显示。 请帮我解决一下这个。 这是代码 -
home.html -
<table class="table">
<thead>
<tr>
<th>SNo.</th>
<th>UserId</th>
<th>Name</th>
<th>Share</th>
<th>Paid</th>
</tr>
</thead>
<tbody ng-repeat="member in members">
<tr>
<td>{{member.sNo}}</td>
<td>{{member.id}}</td>
<td>{{member.name}}</td>
<td>{{member.share}}</td>
<td>{{member.paid}}</td>
</tr>
<tr ng-show="show" class="ng-hide"> //the row which is to be added
<td><span>{{counter}}</span></td>
<td><input type="text" required ng-model="new.id"></td>
<td><input type="text" required ng-model="new.name"></td>
<td><input type="text" required ng-model="new.share"></td>
<td><input type="text" required ng-model="new.paid"></td>
</tr>
</tbody>
</table>
<div><input type="button" value="Add" ng-click="addMember()"/></div>
controller.js -
expmodule.controller('expenseForm', function($scope, sharedProperties) {
var id, expenses = {};
$scope.show = false;
$scope.members = [{
sNo: "1",
id: "abc@gmail.com",
name: "Neha",
share: 200,
paid: 400,
}, {
sNo: "2",
id: "xyz@gmail.com",
name: "Sneha",
share: 200,
paid: 400,
}];
$scope.counter = $scope.members.length++;
$scope.addMember = function () {
$scope.show = true;
return $scope.newRow = true;
}
});
你在找这样的东西吗? http://plnkr.co/edit/jxXX5sWhgmYrANV7ieKM?p=preview
在问题中提供的代码中几乎没有正确的东西。
$scope.counter = $scope.members.length++
这将使数组长度增加1,并且数组中的新对象将是未定义的。 我想你想在新的添加行中显示计数器。 在添加行中可以这样简单地完成 - {{members.length + 1}}
,而不是为此创建新的范围变量。 此外,当添加新成员时,这将始终具有最新值。 它似乎工作正常(见下面的演示)。
当然,您应该将ng-repeat="member in members"
<tr>
而不是<tbody>
(除非您想拥有多个tbodies)。
你应该改变$scope.counter = $scope.members.length++;
to $scope.counter = $scope.members.length + 1;
另见这个简短的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.