【问题标题】:JavaScript array push not working with ng-changeJavaScript 数组推送不适用于 ng-change
【发布时间】:2017-09-14 16:33:05
【问题描述】:

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

查看

<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

【问题讨论】:

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


    【解决方案1】:

    只需更新您的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,
          });
        }
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多