如何使用angularjs动态添加行

How to add the rows dynamically with angularjs?

本文关键字:添加行 动态 angularjs 何使用      更新时间:2023-09-26

我使用代码通过单击添加行来添加行和 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,并且您的控制器也以正确的方式使用。