JavaScript 数组推送不适用于 ng-change

JavaScript array push not working with ng-change

我正在尝试为 class 创建标记列表。当我为每个学生输入分数时, 推送事件有效。每次更改时,都会在数组中创建重复项。我该如何解决?

查看

<tr ng-repeat="student in tabledata">
  <td>{{student.RollNumber}}</td>
  <td>{{student.StudentName}}</td>
  <td ng-repeat="item in Allsubjects">
    <div ng-repeat="enable in student.subjectArray">
      <input type="text" 
             class="form-control" 
             ng-model="SubjectMark" 
             ng-change="internal(item.Id,student.StudentId,SubjectMark)" 
             ng-disabled="item.Elective ==='Optional'&& enable.opted != item.Id" 
             required>
    </div>
  </td>
</tr>

JS

angular.element(document).ready(function() {
      $scope.ArrayMarks = [];
      $scope.ArrayMarks.push({
        'subject': '',
        'student': '',
        'mark': '',
      });
      $scope.internal = function(Sub, Std, score) {
        if ($scope.ArrayMarks[0].subject === '' && $scope.ArrayMarks[0].student === '') {
          $scope.ArrayMarks.push({
            'subject': Sub,
            'student': Std,
            'mark': score,
          });

          $scope.ArrayMarks.splice(0, 1);

        } else {
          for (var i = 0; i < $scope.ArrayMarks.length; i++) {
            if ($scope.ArrayMarks[i].subject === Sub && $scope.ArrayMarks[i].student === Std) {
              $scope.ArrayMarks[i].mark = score;
            } else {
              $scope.ArrayMarks.push({
                'subject': Sub,
                'student': Std,
                'mark': score,
              });

            }
          }
        }
      };

这就是我得到的 (screenshot): there is 9 records instead of 3

只需更新您的 for 循环并确保仅在未找到要更新的条目时才添加新条目。如果未找到更新条目,您当前的解决方案会在每个循环中添加新条目。

$scope.internal = function(Sub, Std, score) {
  if ($scope.ArrayMarks[0].subject === '' && $scope.ArrayMarks[0].student === '') {
    $scope.ArrayMarks.push({
      'subject': Sub,
      'student': Std,
      'mark': score,
    });

    $scope.ArrayMarks.splice(0, 1);

  } else {

    var found = false;

    for (var i = 0; i < $scope.ArrayMarks.length; i++) {
      if ($scope.ArrayMarks[i].subject === Sub && $scope.ArrayMarks[i].student === Std) {
        $scope.ArrayMarks[i].mark = score;
        found = true;
      }
    }

    if (!found) {
      $scope.ArrayMarks.push({
        'subject': Sub,
        'student': Std,
        'mark': score,
      });
    }
  }
};