admin管理员组

文章数量:1200961

I have an array of strings, and I want each of the strings to be bound to an input.

However, editing the input doesn't seem to update the array (isolated scope issues maybe?).

Suggestions?

function Ctrl($scope) {
  $scope.fruits = ['Apple', 'Mango', 'Banana', 'Strawberry'];
}
<script src=".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>

I have an array of strings, and I want each of the strings to be bound to an input.

However, editing the input doesn't seem to update the array (isolated scope issues maybe?).

Suggestions?

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>

Share Improve this question edited May 24, 2019 at 4:39 Dale K 27.2k15 gold badges56 silver badges82 bronze badges asked Feb 17, 2016 at 17:11 DanielDaniel 6,4817 gold badges38 silver badges63 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 23

You need the array reference which you can get from $index. Note, however, that this won't work if any filtering is done on the ng-repeat, as the indexing then is based on the filtered array, not the original.

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

DEMO

Ok, so it seems to me like a case of

'ng-model requires a dot in the model name to work correctly with the scope, otherwise it would create a local scope'

What i would suggest is to change your data structure from plain strings to objects containing the strings as a property, something like :

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

Now, when you bind it to ng-model like this

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

then it will not create any local/child scope, instead it would be able to bind to the title property on the items in the fruits array.

example fiddle: http://jsfiddle.net/HB7LU/24008/

本文标签: javascriptTwo way binding an array of strings in ngrepeatStack Overflow