如何动态添加输入行以将 angularjs ng-model 中的值作为数组项查看和维护 [英] How to dynamically add input rows to view and maintain value in angularjs ng-model as array item

查看:15
本文介绍了如何动态添加输入行以将 angularjs ng-model 中的值作为数组项查看和维护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我希望用户在想要输入新项目时动态添加 行.如下所示,用户单击添加输入项"按钮,并添加了一个新的输入元素,用户可以在其中添加文本.

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>

The app.js code:

app.js 代码:


推荐答案

第一个问题是输入框的绑定问题.由于输入框周围有 ng-repeat,每个输入框都有一个 item 值可用于绑定,这就是你的 ng-model 应该是.您不应为 value 属性分配任何内容.

<input ng-model="item.value" type="text" size="40">

Making that change will at least get the input boxes to display the items.  But typing in the boxes won't update the underlying array.  That's the second problem.

进行更改至少会使输入框显示项目.但是在框中键入不会更新底层数组.这是第二个问题.

The ng-repeat directive prototypically inherits the scope from your controller (read more about scope here). Since your items are primitive strings, the elements in your ng-repeat effectively get copies of the data from the controller, and typing in the boxes updates those copies, not the actual data in the controller.

ng-repeat 指令原型从控制器继承范围(阅读更多关于范围此处).由于您的项目是原始字符串,ng-repeat 中的元素有效地从控制器获取数据的副本,并在框中键入更新这些副本,而不是控制器中的实际数据.>

要解决此问题,只需将您的项目设为对象数组而不是字符串数组.

To fix this, just make your items an array of objects instead of an array of strings.

$scope.items = [
  {value:'First Item'},
  {value: 'Second Item'}
];

然后你会像这样绑定你的文本框:

Then you would bind your textboxes like this:

<input ng-model="item.value" type="text"  size="40">

这是一个 Plunker 展示了它是如何工作的.

Here's a Plunker showing how it works.

这篇关于如何动态添加输入行以将 angularjs ng-model 中的值作为数组项查看和维护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆