如何在AngularJS中追加一个新的表格行
在这篇文章中,我们将看到如何在AngularJS中插入或追加新的表格行,同时通过实例了解其实现。
方法:方法是使用push()方法,将新的行插入数组中。这个数组将作为内容提供给<tr>
元素 。ng-repeat指令,用于将数组的内容提供给表格单元。
例子1:在第一个例子中,使用了一个单列表,内容以其元素的形式存储在数组中。
<!DOCTYPE html>
<html>
<head>
<title>
Appending a new table row in AngularJS
</title>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller",
function (scope) {
scope.rows = ['row-1', 'row-2'];
scope.c = 2;
scope.addRow = function () {
scope.c++;
scope.rows.push('row-' + $scope.c);
};
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to append a new table
row in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller">
<button ng-click='addRow()'>
Click to add
</button><br><br>
<table style="border: 1px solid black;
margin: 0 auto;">
<tr>
<th>Col-1</th>
</tr>
<tr ng-repeat="val in rows">
<td>{{val}}</td>
</tr>
</table><br>
</div>
</div>
</body>
</html>
输出:
例子2:在这个例子中,使用了一个三列的表格,它以Object的格式存储表格的内容。
<!DOCTYPE html>
<html>
<head>
<title>
Appending a new table row in AngularJS
</title>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller",
function (scope) {
scope.rows = [
{ 'ff': '11', 'fs': '12', 'ft': '13' },
{ 'ff': '21', 'fs': '22', 'ft': '23' }
];
scope.c = 2;
scope.addRow = function () {
scope.c++;
scope.rows.push({
'ff': scope.c +
'1', 'fs':scope.c +
'2', 'ft': $scope.c + '3'
});
};
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to append a new table
row in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller">
<button ng-click='addRow()'>
Click to add
</button><br>
<br>
<table style="border: 1px solid black;
margin: 0 auto;">
<tr>
<th>Col-1</th>
<th>Col-2</th>
<th>Col-3</th>
</tr>
<tr ng-repeat="val in rows">
<td>{{val.ff}}</td>
<td>{{val.fs}}</td>
<td>{{val.ft}}</td>
</tr>
</table><br>
</div>
</div>
</body>
</html>
输出: