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).
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
<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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With