【发布时间】:2012-11-22 18:51:56
【问题描述】:
我试图允许用户使用ngRepeat 和ngModel 编辑项目列表。 (See this fiddle.) 但是,我尝试过的两种方法都会导致奇怪的行为:一种不会更新模型,另一种会在每次按键时模糊表单。
我在这里做错了吗?这不是受支持的用例吗?
这是小提琴中的代码,为方便起见复制:
<html ng-app>
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-init="names = ['Sam', 'Harry', 'Sally']">
<h1>Fun with Fields and ngModel</h1>
<p>names: {{names}}</p>
<h3>Binding to each element directly:</h3>
<div ng-repeat="name in names">
Value: {{name}}
<input ng-model="name">
</div>
<p class="muted">The binding does not appear to be working: the value in the model is not changed.</p>
<h3>Indexing into the array:</h3>
<div ng-repeat="name in names">
Value: {{names[$index]}}
<input ng-model="names[$index]">
</div>
<p class="muted">Type one character, and the input field loses focus. However, the binding appears to be working correctly.</p>
</body>
</html>
【问题讨论】:
-
这与stackoverflow.com/questions/12977894/… 非常相似,但是这里的第二种方法是新的,所以它并不完全是重复的。我在那里提供了一个详细的答案(类似于 Artem 的),解释了 ng-repeat 子作用域的工作原理。
-
由于在最终找到此线程之前花费了我合理的谷歌搜索量,我可以将其重命名为:“未从 ngRepeat 输入更新父模型”或“使用 ngRepeat 时未更新模型”或“ ngRepeat 输入未绑定到(父)模型”?也许您对标题有更好的想法?
标签: angularjs angularjs-ng-repeat angularjs-ng-model