简体   繁体   English

ng-repeat中的ng-model被覆盖

[英]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 . 我有一个带有输入字段的表,在每次ng-repeat迭代中都将值设置为ng-model I'm getting correct values in each iteration, but all of the ng-model values are overwritten by the last value of iteration. 我在每次迭代中获取正确的值,但是所有ng-model值都被迭代的最后一个值覆盖。 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): 这是我得到的(屏幕截图): 这就是我要得到的(屏幕截图)

331 is the result of last iteration. 331是最后一次迭代的结果。 It is overwriting previous values. 它正在覆盖先前的值。

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. 等等...它应该为每个元素提供不同的ng-model but If you can share your object it would be more helpful to find the actual error. 但是,如果您可以共享对象,则发现实际错误会更有用。

<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 (ie 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;
};

Yes, it is expected behaviour that last value of the iteration will be assigned to "da" 是的,预期的行为是将迭代的最后一个值分配给“ 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. 在这里,我们只是为student_list数组中每个Student对象创建一个名为“ da”(您使用的名字)的新属性,因此它将具有与该对象相对应的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM