javascript - 如何使用angularjs动态添加行?

标签 javascript jquery html angularjs

我使用代码通过单击添加行来添加行和 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/

相关文章:

javascript - Ajax提交两条信息到php文件

javascript - 修改 jQuery ajax 请求连接头

javascript - slideUp 在 slideToggle 中的 fontawesome 图标上

html - bootstrap text_area 的高度应用不正确

javascript - 在事件处理程序中使用 document.write ?

javascript - 如何根据表单字段类型自动更新价格="number"

javascript - 相当复杂的正则表达式

javascript - 如何根据窗口大小调整网页内容的大小

javascript - jQuery 如何将值设置为前一个输入元素?

jquery - 我的汉堡菜单不起作用