如何动态添加输入行以将 angularjs ng-model 中的值作为数组项查看和维护 [英] How to dynamically add input rows to view and maintain value in angularjs ng-model as array item
问题描述
我有一种情况,我希望用户在想要输入新项目时动态添加 行.如下所示,用户单击添加输入项"按钮,并添加了一个新的输入元素,用户可以在其中添加文本.
I have a situation where I want the user to dynamically add <input>
rows when they want to enter a new item. As shown below, the user clicks the "Add Input Item" button and a new input element is added where the user may add text.
我正在尝试将每个输入元素值与 app.js
中的模型 $scope.items
(一个数组)相关联.在我的 index.html
中,我使用 ng-repeat
加载了 $scope.items
.我不明白的是如何让每个输入/行自动添加到 &由定义为 $scope.items
的模型管理.
I'm trying to associate each input element value to the model $scope.items
(an array) in app.js
. In my index.html
, I load the $scope.items
using an ng-repeat
.
What I do not understand is how I can get each input/row to automatically be added to & managed by the model defined as $scope.items
.
是否可以将每个输入元素映射到与 items
数组相关的 ng-model,如果可以,如何映射?或者,在这种情况下应该使用指令吗?
Is it possible to map each input element to an ng-model that relates to the items
array and, if so, how? Or, should directives be used in this situation?
完整代码和运行时位于 Plunker 此处(以便您可以查看奇怪的输出).
The full code and runtime is on Plunker here (so that you can view the weird output).
来自 index.html
的片段:
<body ng-controller="MainCtrl">
<button ng-click="addInputItem()">+ Add Input Item</button>
<div ng-repeat="item in items">
<input ng-model="items" type="text" value="{{item}}" size="40">
</div>
<pre>items = {{items | json}}</pre>
</body>
<pre>items = {{items |json}}</pre>