Is possible in angular.js on click button add row in table ? I am totally new to angular so maybe is studip question. I know to execute this with jquery and append html text but if there more elegant way to do this in angular when I have html of row (like partial).
3 Answers
In angularjs you want to let your model drive the view, any DOM manipulation should happen within directives (Either your own custom directives or ones that are included within the angular library).
Thankfully angular comes with some very useful directives ready to use. ng-repeat
is well suited to the task of adding a new row to a table within your view.
Consider this Example
HTML
<body ng-controller="ExampleCtrl">
<h1>Person List</h1>
<fieldset>
<legend>Create Person</legend>
<input type="text" ng-model="name" placeholder="Name" ><br />
<input type="number" ng-model="age" placeholder="Age" ><br />
<input type="text" ng-model="title" placeholder="Title" ><br />
<button type="button" ng-click="addPerson()">Add Person</button>
</fieldset>
<table border="1" cellpadding="10">
<thead>
<tr>
<th>
Name
</th>
<th>
Age
</th>
<th>
Title
</th>
<th>
</th>
</tr>
</thead>
<body>
<tr ng-repeat="person in people">
<td>
{{ person.name }}
</td>
<td>
{{ person.age }}
</td>
<td>
{{ person.title }}
</td>
<td>
<button type="button" ng-click="removePerson($index)">Remove Person</button>
</td>
</tr>
</body>
</table>
</body>
Controller
function ExampleCtrl($scope){
$scope.people = [
{name:'Jon', age: 30, title: 'Developer'},
{name:'Mike', age: 37, title: 'Manager'},
{name:'Allen', age: 50, title: 'CEO'}
];
$scope.addPerson = function(){
var person = {
name: $scope.name,
age: $scope.age,
title: $scope.title,
};
$scope.people.push(person);
};
$scope.removePerson = function(index){
$scope.people.splice(index, 1);
};
}
Notice the line ng-repeat="person in people"
angular will render a <tr>
for each item within the people array that is defined on the $scope
of our controller.
If we add another person to our people array, angular will automatically render a new <tr>
within the view during the next digest cycle.
The same will happen if we remove a person from the array. All of the work with DOM elements is isolated within the ng-repeat
directive.

- 6,851
- 1
- 29
- 40
Yes.
The todo
example is a perfect example of this, although using li
and not tables, but it is the same concept.
For when you're new to AngularJS, this Q & A can be helpful if you're an avid jQuery user.

- 1
- 1

- 4,870
- 1
- 28
- 34
-
Agree the todo example should suffice. Basically a directive is necessary any time you plan to manipulate the DOM. – shaunhusain Jan 22 '14 at 22:43
Yes, you can use a button click to add content to a table. Whether it is a best practice or not is debatable.
Basically, your $scope has the model for the table. When the button is clicked, you can push the new data onto the model.
Example : http://codepen.io/calendee/pen/buCHf

- 5,945
- 10
- 44
- 59