我使用代码通过单击添加行来添加行和 2 列。 “我的需要是”, 首先在输入字段中填写值, 之后单击“添加项目”按钮,值必须以表结构显示。 我是初学者。无法使用 for 循环。 谁能解决这个问题。
试试代码:https://jsfiddle.net/idris9791_/a7L832LL/
<html >
<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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body ng-controller="MainController" ng-app="MyApp">
<a href="#" class="button" ng-click="addRow()">Add Row</a>
<form>
First Name : <input name="myInput" ng-model="user.firstName" required>
First Name : <input name="myInput" ng-model="user.lastName" required>
</form>
<table>
<thead>
<tr>
<th>Some Header</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="rowContent in rows">
<td>{{rowContent.firstName}}</td>
<td>{{rowContent.lastName}}</td>
</tr>
</tbody>
</table>
<script>
angular.module('MyApp', [])
.controller('MainController', [ '$scope', function($scope) {
$scope.rows = [];
$scope.counter = 0;
$scope.addRow = function() {
$scope.row.push({
firstName: $scope.firstName,
lastName: $scope.lastName
});
$scope.counter++;
}
}]);
</script>
</body>
</html>
最佳答案
您必须实际将输入的输入值插入 rows
数组:
$scope.row.push({
firstName: $scope.firstName,
lastName: $scope.lastName
});
我会将 html 更新为:
<a href="#" class="button" ng-click="addRow()">Add Row</a>
First Name : <input ng-model="firstName" required>
Last Name : <input ng-model="lastName" required>
然后:
<tr ng-repeat="rowContent in rows">
<td>{{rowContent.firstName}}</td>
<td>{{rowContent.lastName}}</td>
</tr>
确保正确包含 Angular ,并且您的 Controller 也以正确的方式使用。
关于javascript - 如何使用angularjs动态添加行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34906145/