首页 > 解决方案 > 根据angularjs中的数组数据动态创建表单?

问题描述

我从其余 API 数据构造了一个数组,如下所示

arr = [ {'model1': 'value1', 'type': 'text'},
        {'model2': 'true', 'type': 'radio'},
        {'model3': 'value3', 'type': 'text'},
      ];

在这里,我如何为例如第一个元素ng-model名称model1及其valueasvalue1及其类型生成动态形式text/radio

标签: javascriptangularjs

解决方案


首先修复您的数组项属性的名称,以便它们的名称中不包含索引,因为这违背了目的。将数组更改为

arr = [
  {'model': 'value1', 'type': 'text'},
  {'model': 'true', 'type': 'radio'},
  {'model': 'value3', 'type': 'text'},
];

您需要遍历您的数组以生成这样的表单

<form form="arrForm" ng-submit="arrForm.submit()">
  <section ng-repeat="value in arr>
    <label for="value-{{$index}}-model">Model {{$index}}</label>
    <input ng-model="value.model" name="value-{{$index}}-model">

    <section>
      <label for="value-{{$index}}-type">Type {{$index}} </label>
      <input ng-repeat="type in possibleTypes" type="radio" ng-model="value.type" ng-value="type" name="value-{{$index}}-type">
    </section>
  </section>

  <input type="submit" value="Save All" ng-disabled="arrForm.$invalid">
</form>

但是,请考虑使用 AngularJS 表单库。FormlyJS是最好的。


推荐阅读