双向绑定 ng-repeat 中的字符串数组

Two way binding an array of strings in ng-repeat

本文关键字:字符串 数组 ng-repeat 绑定      更新时间:2023-09-26

我有一个字符串数组,我希望每个字符串都绑定到一个输入。

但是,编辑输入似乎不会更新数组(可能是孤立的范围问题?

建议?

function Ctrl($scope) {
  $scope.fruits = ['Apple', 'Mango', 'Banana', 'Strawberry'];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="Ctrl">
    <div style="margin: 20px 0" ng-repeat="fruit in fruits">
      <input type="text" ng-model="fruit" />
    </div>
    Fruits: {{fruits}}
  </div>
</div>

您需要

可以从$index获得的数组引用。但是请注意,如果在ng-repeat上进行了任何过滤,这将不起作用,因为索引是基于过滤的数组而不是原始数组

<div style="margin: 20px 0" ng-repeat="fruit in fruits track by $index">
      <input type="text" ng-model="fruits[$index]" />
</div>

演示

好的,所以在我看来,这就像一个案例

'ng-model 需要模型名称中的点才能与 范围,否则它将创建一个本地范围'

我的建议是将数据结构从纯字符串更改为包含字符串作为属性的对象,例如:

 $scope.fruits = [
    {'title':'Apple'},
    {'title':'Mango'},
    {'title':'Banana'},
    {'title':'Strawberry'},
    ];

现在,当你像这样将它绑定到 ng 模型时

<div style="margin: 20px 0" ng-repeat="fruit in fruits">
      <input type="text" ng-model="fruit.title" />
</div>

然后,它不会创建任何本地/子作用域,而是能够绑定到 fruits数组中项的 title 属性。

示例小提琴:http://jsfiddle.net/HB7LU/24008/