AngularJS:如何以表格形式表示和保存每行的对象

时间:2014-12-04 15:29:44

标签: javascript angularjs forms html-table angularjs-ng-repeat

我需要有departments的表格形式,其中部门数量有限,日期可用。在所有这些部门中,需要将一些部门分配给学生,一旦完成,就需要提交表格。提交时,表中的每一行都需要添加到assignedDepartments集合的集合中。

以下是我需要assignedDepartments集合查看是否已分配两个部门的方法:

var assignedDepartments= [
    { "name": "Rohit", "age": 24, "department": "Computer Science", "isAssigned": true}, 
    { "name": "Matt", "age": 23, "department": "Engineering Physics", "isAssigned": true},
    { "name": "Rubi", "age": 32, "department": "Humanity", "isAssigned": false}
]

departments集合可用于我使用ng-repeat进行迭代:

<form name="assignedDepartmentsForm">
  <table class="table table-hover">
    <thead>
      <tr>
        <th>
             Name
        </th>
        <th>
             Age
        </th>
        <th>
             Department
        </th>
      </tr>
     </thead>
    <tbody>
      <tr ng-repeat="department in departments">
        <td>
              <input  type="text" ng-model="name" />
        </td>
        <td>
             <input  type="number" ng-model="age" />
        </td>
        <td>
            {{ department}}
        </td>
        <td>
            <input type="checkbox" ng-model="isAssigned" />
        </td>
      </tr>
    </tbody>
  </table>
<form>

有人可以帮我创建departments的表格表格,其中每一行都被表示并保存为表单提交中的对象。

1 个答案:

答案 0 :(得分:2)

将字符串数组转换为对象数组(如下所示)。然后,您可以更轻松地向对象添加更多字段。

[
  {"department":'Computer Science'},
  {"department":'Engineering Physics'},
  {"department":'Humanity'}
]

您现在仍然可以使用html代码。你只需要调整你的控制器。

function formCtrl($scope) {
  $scope.departments = angular.copy(data2);
  $scope.submit = function() {
  $scope.assignedDepartments = [];
     angular.forEach($scope.departments, function(d) {
        if (d.isAssigned) {
           $scope.assignedDepartments.push(d);
        }
     })
  }
  $scope.assignedDepartments = [];
}

以下是代码示例:http://jsbin.com/pegonisale/1/edit?html,js,output