Reputation: 51
I need a table whose rows can be added dynamically on a button click and the table itself can be re-created and shown on the page with another button click
I have created the following HTML:
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Add Rows</title>
<link href="http://cdn.foundation5.zurb.com/foundation.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
</head>
<body ng-controller="MainController">
<a href="#"
class="button"
ng-click="addRow()">
Add Row</a>
<a href="#"
class="button"
ng-click="addTable()">
Add Table </a>
<div ng-repeat="data in table">
<table>
<thead>
<tr>
<th width="200">Name</th>
<th width="200">Age</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="rowContent in rows">
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
</tbody>
</table>
<div>
</body>
</html>
Here's my Controller:
angular.module('MyApp', [])
.controller('MainController', [ '$scope', function($scope) {
$scope.table=['Table 1'];
$scope.rows = ['Row 1'];
$scope.counter = 3;
$scope.addRow = function() {
$scope.rows.push('Row ' + $scope.counter);
$scope.counter++;
}
$scope.addTable = function() {
$scope.table.push('Table ' + $scope.counter);
$scope.counter++;
}
}]);
Everything works fine except that when I click on Add Table , The previous table along with the added rows gets copied. I want to just have the initial instance of the table with just one row to add age and name. Please help:
Code pen Link :http://codepen.io/anon/pen/wBwXJP
Upvotes: 2
Views: 6350
Reputation: 466
if you make an object from the table by doing this
$scope.tables=[{name: "table 1"}];
$scope.tables[0].rows=['row1']
this will make it posible to add a row to $scope.tables[0].rows that way it will only be added to the first for new you just push
$scope.tables.push({name: 'Table ' + $scope.counter});
and it will create a whole new table
and you have to change rows in
<tr ng-repeat="rowContent in table.rows">
i hope this will help you in the right way
here i edited your code to make it the way i think it is best
Upvotes: 2