JavaScript数组推送无法使用ng-change

时间:2017-09-14 08:17:20

标签: javascript angularjs arrays angularjs-ng-repeat angularjs-ng-change

我尝试为课程创建标记列表。当我为每个学生输入分数时, 推送活动有效。每次更改时,都会在数组中创建重复项。我该如何解决这个问题?

视图

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,
              });

            }
          }
        }
      };

JS

bottom:0

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

1 个答案:

答案 0 :(得分: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,
      });
    }
  }
};