如何使用angularjs动态创建表单

时间:2015-01-09 08:41:44

标签: javascript angularjs

我试图弄清楚如何根据服务器返回的字段数组动态创建表单。

像这样的东西

[{
  id: "title",
  type: "text", /* Map to Input type=text */
  regex: "/^[a-zA-Z]+/"
},{
  id: "summary",
  type: "memo", /* Map to Textarea */
  regex: "/^[a-zA-Z]+/"
},{
  id: "priority",
  type: "list", /* Map to Select */
  options: [1,2,3,4,5]
}]

即使使用ng-repeat,我也无法找到一种很好的方法。一旦表单有大约30个字段和15个以上不同的输入类型,它就会非常难看。

什么是“Angular”方式,或者我应该在服务器上动态生成controller.js和template.html吗?

1 个答案:

答案 0 :(得分:0)

试试这个。这不是答案,只是一种方法。希望它可以帮到你。

HTML:

<div ng-repeat="person in person">
<form class="form-group" name="signinForm">
<label>Name:
<input class="form-control" ng-model="person.name" type="text">
</label>
<label>Male:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="male">
</label>
<label>Female:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="female">
</label><br>
<label>Age
<input class="form-control" ng-model="person.age" type="number">
</label>
</form>
<button type="button" ng-click="addPerson()">Add More</button>
</div>

JS:

 $scope.initialize = [{}];
    $scope.person = {};
    $scope.addPerson = function(){
        $scope.initialize.push({});// adding more similar fields.
    }
相关问题