angularjsangularjs-ng-repeatangular-ngmodelangularjs-ng-init

ng-model overwritten within ng-repeat


I have a table with an input field, I'm setting values to ng-model in each iteration of ng-repeat. I'm getting correct values in each iteration, but all of the ng-model values are overwritten by the last value of iteration. How can I solve this ?

view

<tr ng-repeat="student in students_list">
        <td>{{student.Rollnumber}}</td>
        <td>{{student.Name}}</td>
        <td ng-repeat="item in Allsubjects" >      
            <input   type="text" class="form-control" ng-model="da" 
                  ng-init="alert(student.Id)">
        </td>
</tr>

controller

$scope.alert = function(id)
{
    $scope.da =id;
};

This is What I'm getting (screenshot): This is What I'm getting (screenshot)

331 is the result of last iteration. It is overwriting previous values.


Solution

  • Yes, it is expected behaviour that last value of the iteration will be assigned to "da"

    You can resolve this by

    <tr ng-repeat="student in students_list">
            <td>{{student.Rollnumber}}</td>
            <td>{{student.Name}}</td>
            <td ng-repeat="item in Allsubjects" >      
                <input   type="text" class="form-control" ng-model="student['da']" 
                      ng-init="alert(student)">
            </td>
    </tr> 
    

    and the alert function

    $scope.alert = function(student)
    {
        student["da"] = student.id;
    };
    

    Here, we are just creating a new property named "da"(took name you used) for every object of student in student_list array, so it will have value respective to it's object.