Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete.
A challenge arises when editing and saving a row causes it to disappear. Attempts were made to add values manually to table rows using jQuery, but without success.
You can access the code on Codepen Link.
This is the html page:
<div class="container" ng-app="trial">
<table class="table table-hover" ng-controller="newTrial">
<tr>
<th class="col-md-3">Name</th>
<th class="col-md-2">Age</th>
<th class="col-md-5">Description</th>
<th class="col-md-2">Actions</th>
</tr>
<tr ng-repeat="entry in entryList">
<td ng-hide="edit[$index]">{{entry.name}}</td>
<td ng-hide="edit[$index]">{{entry.age}}</td>
<td ng-hide="edit[$index]">{{entry.desc}}</td>
<td ng-hide="edit[$index]">
<button class="btn btn-primary" ng-click="editEntry($index)">Edit</button>
<button class="btn btn-danger" ng-click="deleteEntry($index)">Delete</button>
</td>
<td ng-show="edit[$index]">
<input type="text" class="form-control" ng-value="entry.name" id="nameEdit$index" />
</td>
<td ng-show="edit[$index]">
<input type="text" class="form-control" ng-value="entry.age" id="ageEdit$index" />
</td>
<td ng-show="edit[$index]">
<input type="text" class="form-control" ng-value="entry.desc" id="descEdit$index" />
</td>
<td ng-show="edit[$index]">
<button class="btn btn-success" ng-click="saveEntry($index)">Save</button>
<button class="btn btn-warning" ng-click="cancelEntry($index)">Cancel</button>
</td>
</tr>
</table>
</div>
This is the javascript file:
var app = angular.module('trial', []);
app.controller('newTrial', ["$scope", function($scope){
$scope.edit = [false, false, false];
$scope.entryList = [
{
name: "ABC",
age: 30,
desc: "Something he does"
},
{
name: "DEF",
age: 35,
desc: "Something he does not do"
},
{
name: "GHI",
age: 32,
desc: "Something he is good at"
}
];
$scope.editEntry = (i) => {
$scope.edit[i] = true;
};
$scope.deleteEntry = (i) => {
$scope.edit.splice( i , 1 );
$scope.entryList.splice( i , 1 );
};
$scope.saveEntry = (i) => {
$scope.entryList[i].name = angular.element("nameEdit"+i).val();
$scope.entryList[i].age = angular.element("ageEdit"+i).val();
$scope.entryList[i].desc = angular.element("descEdit"+i).val();
$scope.edit[i] = false;
};
$scope.cancelEntry = (i) => {
$scope.edit[i] = false;
};
}]);