ng-model overwritten within ng-repeat

567 Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

I think the source of your problem is your object definition.

try to create your objects like this

$scope.student_list = [
  student1 = {
    Rollnumber : 9999,
    Name : "Foo", 
    sub1 : 0 
  }
]

etc... It should give you a different ng-model for each element. but If you can share your object it would be more helpful to find the actual error.

0
On
<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"+item 
                  ng-init="alert(student.Id,)">
        </td>
</tr>

Here we add dynamic value to the model (i.e item), now it will not override the model values, and you can easily get it by your defined function:

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