suman goud suman goud - 2 months ago 6
AngularJS Question

How to change Add button to remove after adding in Angularjs

want to show only add button in first row ,
when i click add ,add new row and change or hide add button to remove.
continuously same. and first row should not remove and show add button

div ng-app="ReceiptsApp">
<div ng-controller="ReceiptsController">
<table class="tableData">
<tr ng-repeat="r in rvm">
<td>
<select ng-model="c" style="width:150px;height:22px;" ng-options="c.name for c in sample">
<option value="">--Select--</option>
</select>
</td>
<td>
<input type="text" lass="input-large" ng-model="c.Address" name="Address" />
</td>
<td>
<input type="text" class="input-large" ng-model="c.Mobile" name="Mobile" />
</td>
<td>
<button type="button" class="btn btn-default" ng-click="addRow($index,c)">Add</button>

</td>
<td>
<button type="button" class="btn btn-default" ng-click="deleteRow($index)">Remove</button>

</td>


</tr>
</table>

</div>
</div>


JS

var ReceiptsApp = angular.module('ReceiptsApp', []);

ReceiptsApp.controller('ReceiptsController', function ($scope) {

$scope.sample = [{
id: '1',
name: 'Bhanu',
Address: 'Moosapet',
Mobile: '9246100100'
}, {
id: '2',
name: 'Madhu',
Address: 'Uppal',
Mobile: '9000330653'
}, {
id: '3',
name: 'Geetha',
Address: 'Sanath Nagar',
Mobile: '9912340519'
}];
$scope.rvm = [{}];
$scope.addRow = function (index, c) {
if ($scope.rvm.length == (index + 1)) {
$scope.rvm.push({
});
}
}

$scope.deleteRow = function ($index) {
$scope.rvm.splice($index, 1);
}


});


i have posted code here

https://jsbin.com/yamobarapo/edit?html,js,output

Answer

A cheap & fast trick would be to make the Add button show only for the last element of ng-repeat like this:

<td ng-if="$last">
    <button type="button" class="btn btn-default"  ng-click="addRow($index,c)">Add</button>            
</td>
<td ng-if="!$last">
    <button type="button" class="btn btn-default" ng-click="deleteRow($index)">Remove</button>          
</td>

I have also updated your JSBin to see it in action.