如何使用递增的 ng 模型动态创建多个表单输入字段

How to dynamically create multiple form input fields with incremented ng-models?

本文关键字:创建 表单 字段 输入 动态 模型 何使用 ng      更新时间:2023-09-26

阅读本文后,我了解如何使用 ng-repeat 动态添加表单字段。

我想知道如何以递增ng-model值动态创建多个表单元素。

例如,将通过单击按钮创建以下内容。

<input ng-model="vm.foo.bar1.first">
<input ng-model="vm.foo.bar1.second">
<input ng-model="vm.foo.bar1.third">
<input ng-model="vm.foo.bar1.fourth">
<input ng-model="vm.foo.bar2.first">
<input ng-model="vm.foo.bar2.second">
<input ng-model="vm.foo.bar2.third">
<input ng-model="vm.foo.bar2.fourth">
<input ng-model="vm.foo.bar3.first">
<input ng-model="vm.foo.bar3.second">
<input ng-model="vm.foo.bar3.third">
<input ng-model="vm.foo.bar3.fourth">

如何做到这一点?

我建议重组您的ViewModel以vm.foo.bar数组。那么这将是微不足道的:

<div ng-repeat="item in barItems">
  <input ng-model="vm.foo.bar[$index].first">
  <input ng-model="vm.foo.bar[$index].second">
  <input ng-model="vm.foo.bar[$index].third">
  <input ng-model="vm.foo.bar[$index].fourth">
</div>

或者,如果你坚持,那么也

<div ng-repeat="item in barItems" ng-init="outerIdx = $index">
   <input ng-repeat='p in ["first", "second", "third", "fourth"]' 
          ng-model="vm.foo.bar[outerIdx][p]">
</div>

(我在这里假设,与firstsecond等不同,bar s 的数量是未知的 - 因此数组是更好的选择)

编辑

如果你真的想要,你也可以vm.foo一个包含属性bar1bar2等的对象:

<div ng-repeat="item in [1, 2, 3, 4]">
  <input ng-model="vm.foo['bar' + item].first">
  <input ng-model="vm.foo['bar' + item].second">
  <input ng-model="vm.foo['bar' + item].third">
  <input ng-model="vm.foo['bar' + item].fourth">
</div>

但不要忘记首先在控制器中创建vm.foo对象:

this.foo = {};

当我必须这样做时,我使用 $index 来控制事物的名称。虽然我从未尝试过这个确切的代码,但这应该有效。

<input ng-model='vm.foo.bar3[$index]'></input>

每当您执行 ng-repeat 时,$index都会出现,并且只是列表项的索引。因此,这最终应该使ng模型成为vm.foo.bar3.0

的任何模型。

在我看来,您应该在控制器中创建模型数组。

$scope.vm.foo = [{
    bar1: [{
        first: '',
        second: '',
        ...
       },
    bar2: ...
  ],
}]

然后在您的视图中迭代您的选项卡:

<div ng-repeat="elem in foo">
    <div ng-repeat="input in elem">
        <input ng-model="input">
    </div>
</div> 

希望对您有所帮助!