AngularJS | Dynamic table with add/remove
Dynamic table with in-line form
by Duke Dinh
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<body ng-app="myapp" ng-controller="ListController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form>
<div style="height: 200px; overflow: auto;">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</th>
<th>Rule</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="rule in rules">
<td>
<input type="checkbox" ng-model="rule.selected" />
</td>
<td>
<span>{{rule.rule}}</span>
</td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<input ng-hide="!rules.length" type="button" class="btn btn-sm btn-danger pull-right" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-sm btn-primary addnew pull-right" value="Add New">
<input type="submit" class="btn btn-sm btn-primary addnew pull-right" ng-click="printObject()" value="Send">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
CSS
.btn-primary {
margin-right: 10px;
}
.container {
margin: 20px 0;
}
JavaScript
var app = angular.module("myapp", []);
app.controller("ListController", ['$scope', function($scope) {
$scope.rules = [{
'rule': '1',
'selected': true
}, {
'rule': '2'
}, {
'rule': '3'
},{
'rule': '4'
},{
'rule': '5'
},{
'rule': '6'
}];
$scope.addNew = function(personalDetail) {
$scope.rules.push({
'rule': ""
});
};
$scope.remove = function() {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.rules, function(selected) {
if (!selected.selected) {
newDataList.push(selected);
}
});
$scope.rules = newDataList;
};
$scope.checkAll = function() {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.rules, function(personalDetail) {
personalDetail.selected = $scope.selectedAll;
});
};
$scope.printObject = function () {
console.log($scope.rules);
}
}]);