1

I trying to create mark list for a class. When I enter marks for each student, the push event works. On each change, there will be creating duplication in the array. How can I solve this?

View

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

            }
          }
        }
      };

This is What I'm getting (screenshot): there is 9 records instead of 3

1 Answer 1

3

Just update your for loop and ensure adding new entries only if no entry to update was found. Your current solution adds new entries on each loop if no update entry was found.

$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,
      });
    }
  }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.