AngularJs:添加动态行,防止重复

时间:2018-08-06 19:33:56

标签: javascript angularjs

我创建了一个html表,用户可以添加动态列和行。当您单击添加列时,它会添加一列,并且当您在第一行中开始键入时,应该创建一个新行。

这是我的jsfiddle:http://jsfiddle.net/ydevb1Lx/

此处添加行存在一些问题。当用户键入内容时,我将创建一个新行。但是,当用户键入第二个字母时,它将再次创建另一行,依此类推。同样在退格键上,它再次创建一个新行。不知道这里发生了什么。

我无法找到的第二件事是如何验证表,以便仅ID列没有任何重复项。由于我正在使用ng-change事件,因此如何检查表中是否已经存在相同的ID并显示某种警报。下面是相关代码:

HTML表格:

 <table class="table table-bordered" ng-form="targetTableForm" ng-class="{submitted: targetTableSubmitted}">
      <colgroup>
        <col class="unique-id">
      </colgroup>
      <thead>
        <tr>
          <th class="unique-id">Name #</th>
          <th contenteditable="true" ng-repeat="c in targetTable.columns" ng-model="c.label"></th>
          <!--<th class="view-next-set"><a href="#">...</a></th>-->
          <td class="center add-column"><a href ng-click="open()">+ Add Column</a></td>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="r in targetTable.rows">
          <td contenteditable="true" ng-model="r.tableId"  ng-change="r.tableId? addNewRow(r.tableId, r): undefined"></td>
          <td contenteditable="true" ng-repeat="column in targetTable.columns" ng-required="!$parent.$last"></td>
          <!--<td class="blank" colspan="2"></td>-->
        </tr>
      </tbody>
    </table>

用于创建添加行的代码:

  $scope.addNewRow = function(value, row) {
    if (!value || value === "" || typeof value !== 'string') return;
    $scope.targetTable.rows.push({});

    row.id = $scope.targetTable.uniqueIdCounter++;
  };

下面是我初始化数组的方法:

  var table = {
  id: 0,
  name: "table 1",
  columns: [],
  rows: [{}],
  uniqueIdCounter: 1037
};

$scope.tables = [table];
$scope.targetTable = $scope.tables[0];

2 个答案:

答案 0 :(得分:1)

addNewRow中添加新行之前,请检查最后一行的值是否为空。如果为空,请勿添加。您遇到的问题是您正在addNewRow中调用ng-change函数。每次更改输入值时,它将调用该函数。但是您没有检查最新的行是否为空。

对于第二个问题,您可以使用ng-blur指令。我创建了两个额外的函数checkIDforDups,用于添加css类,以及checkForDups,用于检查tableId中的重复项。

这是Jsfiddle:http://jsfiddle.net/ydevb1Lx/51/

答案 1 :(得分:0)

在推送行value.length == 1

之前检查条件
if(value.length ==1){

     $scope.targetTable.rows.push({});
}