我正在尝试更新显示在 ng-repeat
中的 $scope 对象数组在页面上使用包含数组内容的输入元素。 plunker 示例可以在这里找到:Plunker demo (我的问题的基本、精简示例)
我定义了以下设置对象:
$scope.settings = {
list: ['list item one', 'list item two', 'list item three']
};
我在页面上表示这样的数据:
<ul>
<li ng-repeat="item in settings.list">
<input type="text"
value="{{item}}"
ng-model="singleItem"
ng-change="settings.list[$index] = singleItem" />
<a href="javascript:void(0)">delete</a>
</li>
</ul>
我的目标是最初填充 <input>
内容为 $scope.settings.list
的字段每当一个项目被改变时更新数组,但我还没有想出如何在 View 中。省略 ng-model
和 ng-change
在输入上正确呈现文本框中的输入值,但在进行更改时不会修改数组。
旁注:
在 Plunker 示例中,我有 $watch
在设置对象上。在我的实际代码中,这用于使用 $cookies
module 更新“设置 cookie” .示例中省略了 Cookie,但出于调试目的,我保留了 watch 。
最佳答案
您的方法存在两个主要问题。首先是 ngRepeat 使用继承范围,因此原始值(如字符串和数字)不能很好地发挥作用。您应该将对象数组而不是基元数组传递给 ngRepeat。您的第二个问题是绑定(bind)到输入的过于复杂的方式。您只需要这样做:
$scope.settings = {
list: [
{ val: 'list item one'},
{ val: 'list item two'},
{ val: 'list item three'}
]
};
然后在你看来:
<ul>
<li ng-repeat="item in settings.list">
<input type="text" ng-model="item.val"></input>
<a ng-click="remove($index)">delete</a>
</li>
</ul>
这是一个修改后的插件:http://plnkr.co/edit/ZGFjBnVSwM4hNSgVSOCW?p=preview .
关于angularjs - 修改在 ng-repeat 中显示的对象内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14409815/