双向绑定不适用于 ng-repeat [英] two way binding not working with ng-repeat

查看:20
本文介绍了双向绑定不适用于 ng-repeat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 ng-repeat 列表,其中我将当前列表项的值分配给控制器上的另一个属性,如下所示:

I have a simple ng-repeat list, in which i am assigning current list item value to another property on the controller as follows:

  <li ng-repeat="num in list">
    <input type="text" ng-init="value = num" ng-model="value" />
    <button type="button" class="btn btn-primary" ng-click="save()">Save</button>
  </li>

但是当我单击保存"按钮时,我为 $scope.value 设置了默认值.我希望显示特定输入文本的值.

But when i click the Save button i get default value set for $scope.value. I expect the value for the particular input text to be displayed.

这是控制器:

 angular.module('myApp', [])
    .controller('MyController', function($scope){
      $scope.value = false;
      $scope.list = [0, 1, 2, 3, 4];
      
      $scope.save = function() {
         alert($scope.value);
      }
    });

如何在调用保存函数时访问控制器中输入项的更新值.

How can i access the updated value of a input item in my controller on save function call.

这是相同的 plunker:plnkr

Here is the plunker for the same: plnkr

更新:我希望将值提取到控制器而不将其作为参数传递.

Update: I am expecting the value to be fetched to controller without passing it as a parameter.

推荐答案

哇,我不敢相信大多数人都错过了这个.如果您使用的是 Angular 1.2,那么您一定要检查 ngRepeat 指令中的 track by 关键字.

Wow I can't believe most people have missed this. If you are using Angular 1.2 then you should definitely check out track by keyword in your ngRepeat directive.

<li ng-repeat="num in list track by $index">
    <input type="text" ng-model="list[$index]" />
    <button type="button" class="btn btn-primary" ng-click="save()">Save</button>
</li>

底线在绑定时远离原始类型,因为它会给您带来同步问题.

Bottom line is stay away from primitive types when binding since it will give you sync issues.

伙计们,请花更多的时间和精力来研究您的解决方案,而不是仅仅为了积分而发帖.

Fellas please put more time and effort into researching your solutions instead of just posting for points.

希望这有帮助!

这篇关于双向绑定不适用于 ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆